Commit 7122f040 authored by Lucas Serrano's avatar Lucas Serrano

[digicode] On confie la gestion de digicode à l'intranet 2

 * digicode.py appelle désormais la fonction create de l'intranet 2.
 * digicode_server2.py est renommé en digicode_server.py.
 * Edition de gen_code.py pour le rendre compatible avec le nouveau digicode.py.
parent dbf4496b
......@@ -32,14 +32,19 @@ import os
import commands
import string
import random
import requests
sys.path.append("/usr/scripts/")
import cranslib.utils.files
import secrets_new
digicode_pass = secrets_new.get("digicode_pass")
# #############################################################
# CONSTANTES
# #############################################################
CODES_SERVERS = ["zamok", "asterisk"]
CODES_DIR = "/usr/scripts/var/digicode/"
CREATION_LINK = "https://intranet2.crans.org/digicode/create/"
CERTIFICATE = "/etc/ssl/certs/cacert.org.pem"
# #############################################################
# EXCEPTIONS
......@@ -92,32 +97,9 @@ def save_code(code, monString=""):
# et l'enregistre
#
def gen_code(user_name):
""" Genere un code au hasard l'enregistre avec user_name dans le fichier"""
# Generation du code et ecriture du code
rand=random.Random()
# Graine automatique avec le temps
rand.seed()
for i in range(1000):
# On genere un code
code = rand.randint(100000, 999999)
# Si le code est libre, on sort de la boucle
if not os.path.exists( os.path.join( CODES_DIR, str( code ) ) ):
break
else:
# Pas de code disponible
print ("ERROR: Il n'y a pas de code disponible" )
sys.stderr.write ("ERROR: Il n'y a pas de code disponible" )
try:
sys.stderr.write("DEBUG: Un rapport de bug a ete automatiquement envoye.\n")
except:
sys.stderr.write("ERROR: Impossible d'envoyer le rapport de bug.\n")
sys.stderr.write("ERROR: Plus de codes disponibles.\n")
sys.stderr.write("ERROR: Penser a ouvrir a l'adherent debite...\n")
return
save_code(code, user_name)
return code
"""On contacte l'intranet 2 pour générer le code et on récupère le résultat"""
response = requests.post(CREATION_LINK, data={'password':digicode_pass, 'user':user_name}, verify=CERTIFICATE, timeout=2)
return response.content
# ###############################
......
#!/usr/bin/env python
#!/bin/bash /usr/scripts/python.sh
import time
import os
import sys
import SocketServer
import requests
import gestion.secrets_new
digicode_pass = gestion.secrets_new.get('digicode_pass')
CODES = "/var/impression/codes"
PIDFILE = "/var/run/digicode.pid"
HOST, PORT = "zamok.adm.crans.org", 1200
DIGICODE_LINK = "https://intranet2.crans.org/digicode/delete/"
CERTIFICATE = "/etc/ssl/certs/cacert.org.pem"
def log(message = "", logfile = "/var/log/crans/digicode.log"):
"""Log a message to the default logfile"""
......@@ -41,19 +47,11 @@ class VigileHandler(SocketServer.BaseRequestHandler):
# if data starts with o, opened door validation, else should
# be a code
if not data.startswith("o"):
valide, contents = self.check_code(data)
if valide:
response = requests.post(DIGICODE_LINK, data = {'password' : digicode_pass, 'code' : data}, verify = CERTIFICATE, timeout=0.5)
if response.content == u'Code Successfully Deleted':
socket.sendto("passoir,o=1", self.client_address)
log("valid code! (%s)" % contents.strip())
def check_code(self, data):
"""Check the given code against the available codes list."""
path = os.path.join(CODES, data)
if os.path.exists(path):
contents = open(path).read()
os.remove(path)
return True, contents
return False, ""
log("%s -- %s" % (data, response.content))
if __name__ == "__main__":
# do the UNIX double-fork magic, see Stevens' "Advanced
......
#!/usr/bin/env python
import time
import os
import sys
import SocketServer
import requests
sys.path.append('/etc/crans/secrets')
from secrets import digicode_pass
CODES = "/var/impression/codes"
PIDFILE = "/var/run/digicode.pid"
HOST, PORT = "zamok.adm.crans.org", 1200
DIGICODE_LINK = "https://intranet2.crans.org/digicode/delete/"
CERTIFICATE = "/etc/ssl/certs/cacert.org.pem"
def log(message = "", logfile = "/var/log/crans/digicode.log"):
"""Log a message to the default logfile"""
log = open(logfile, "a")
if message:
log.write("%s %s\n" % (time.strftime("%b %d %H:%M:%S"), message))
log.flush()
log.close()
def runme():
os.chdir(CODES)
#lpadmin
os.setegid(108)
#freerad
os.seteuid(120)
log("Starting server!")
server = SocketServer.UDPServer((HOST, PORT), VigileHandler)
server.serve_forever()
class VigileHandler(SocketServer.BaseRequestHandler):
"""Handler class for SocketServers, answering to door requests"""
def handle(self):
"""Handle the request the door sent us"""
data = self.request[0].lower()
socket = self.request[1]
log("%s wrote: %s" % (self.client_address[0], data))
# if data starts with o, opened door validation, else should
# be a code
if not data.startswith("o"):
response = requests.post(DIGICODE_LINK, data = {'password' : digicode_pass, 'code' : data}, verify = CERTIFICATE)
if response.content == u'Code Successfully Deleted':
socket.sendto("passoir,o=1", self.client_address)
log("%s -- %s" % (data, response.content))
if __name__ == "__main__":
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# decouple from parent environment
os.chdir("/") #don't prevent unmounting....
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
#print "Daemon PID %d" % pid
open(PIDFILE,'w').write("%d"%pid)
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# start the daemon main loop
runme()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
import sys
sys.path.append('/usr/scripts/impression')
sys.path.append('/usr/scripts/gestion')
from digicode import gen_code
......@@ -9,4 +9,4 @@ from user_tests import getuser
if __name__ == '__main__':
# génère un nouveau code et l'affiche
print gen_code('%s via %s'%(getuser(),os.path.abspath(__file__)))
print gen_code(getuser())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment