Exemple #1
0
 def verify_auth_token(token):
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return None
     return User.query.get(data['id'])
Exemple #2
0
def get_authorization(user):
    serializer = Serializer(secret_key=app.config['SECRET_KEY'],salt=config.SECURITY_PASSWORD_SALT)
    authorization_code = "%s-%s" % (user.username,user.email)
    authorization_code = serializer.dumps(authorization_code)
    digester  = hashlib.md5()
    digester.update(authorization_code)
    return digester.hexdigest()
Exemple #3
0
 def confirm(self, token):
     s = Serializer(current_app.config["SECRET_KEY"])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get("confirm") != self.id:
         return False
     self.confirmed = True
     db.session.add(self)
     return True
Exemple #4
0
    def verify_token_for(token):

        if token == None or len(token) <= 0 : return False
        serializer = Serializer(SECURITY_PASSWORD_SALT)
        data = serializer.loads(token,SECURITY_PASSWORD_SALT)
        if data != None:
            id = data.id
            username = data.username
            email = data.email
            currentUser = system.user_datastore.find_user(id=id,username=username,email=email)
            if currentUser != None: return True
            else: return False
        return False
Exemple #5
0
 def confirm_account(self, token):
     """Verify that the provided token is for this user's id."""
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except (BadSignature, SignatureExpired):
         return False
     if data.get('confirm') != self.id:
         return False
     self.confirmed = True
     db.session.add(self)
     db.session.commit()
     return True
Exemple #6
0
 def reset_password(self, token, new_password):
     """Verify the new password for this user."""
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except (BadSignature, SignatureExpired):
         return False
     if data.get('reset') != self.id:
         return False
     self.password = new_password
     db.session.add(self)
     db.session.commit()
     return True
Exemple #7
0
    def verify_auth_token(token):
        """Validate the token whether is night."""

        serializer = Serializer(
            current_app.config['SECRET_KEY'])
        try:
            # serializer object already has tokens in itself and wait for
            # compare with token from HTTP Request /api/posts Method `POST`.
            data = serializer.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None

        user = User.query.filter_by(id=data['id']).first()
        return user
Exemple #8
0
def build_local_part(name, uid):
    """Build local part as 'name-uid-digest', ensuring length < 64."""
    key = current_app.config["SECRET_KEY"]
    serializer = Serializer(key)
    signature = serializer.dumps(uid)
    digest = md5(signature)
    local_part = name + "+" + uid + "-" + digest

    if len(local_part) > 64:
        if (len(local_part) - len(digest) - 1) > 64:
            # even without digest, it's too long
            raise ValueError(
                "Cannot build reply address: local part exceeds 64 characters"
            )
        local_part = local_part[:64]

    return local_part
Exemple #9
0
 def change_email(self, token):
     """Verify the new email for this user."""
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except (BadSignature, SignatureExpired):
         return False
     if data.get('change_email') != self.id:
         return False
     new_email = data.get('new_email')
     if new_email is None:
         return False
     if self.query.filter_by(email=new_email).first() is not None:
         return False
     self.email = new_email
     db.session.add(self)
     db.session.commit()
     return True
Exemple #10
0
 def change_email(self, token):
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get('change_email') != self.id:
         return False
     new_email = data.get('new_email')
     if new_email is None:
         return False
     if self.query.filter_by(email=new_email).first() is not None:
         return False
     self.email = new_email
     self.avatar_hash = hashlib.md5(
         self.email.encode('utf-8')).hexdigest()
     db.session.add(self)
     return True
Exemple #11
0
def rest_login():
    username = request.form['username']
    password = request.form['password']
    user = user_datastore.find_user(username=username)
    if user is not None and utils.verify_password(password,user.password):
        session['current_active_user'] = user
        session['rest_user'] = {'user':user,'authorization':None}
        serializer = Serializer(secret_key=app.config['SECRET_KEY'],salt=config.SECURITY_PASSWORD_SALT)
        authorization_code = "%s-%s" % (user.username,user.email)
        authorization_code = serializer.dumps(authorization_code)
        found_sites = UserSite.objects(user=user)
        sites = []
        for found in found_sites:
            site = {'name':found.name,'url':found.url,'username':found.username,'password':found.password,'folder':found.folder
                    ,'settings':{'favourite':found.settings['favourite'],'autologin':found.settings['autologin'],'autofill':found.settings['autofill']},
                    'id':str(found.id)}
            if found.fields is not None and len(found.fields) > 0:
                site['fields'] = []
                for field in found.fields:
                    site['fields'].append({
                        'name':field['name'],
                        'value':field['value'],
                        'type':str(field['type']).lower()
                    })
            else:
                site['fields'] = []
                site['fields'].append({'name':'username','type':'text','value':site['username']})
                site['fields'].append({'name':'password','type':'text','value':site['password']})
            sites.append(site)

        digester  = hashlib.md5()
        digester.update(authorization_code)
        authorization = digester.hexdigest()
        account = {'name':user.name,'email':user.email,'username':user.username,'authorization':authorization}
        response = Response(dumps({'success':True,'sites':sites,'account':account,'authorization':authorization}),status=200,mimetype='application/json')
        response.headers['Authorization'] = digester.hexdigest()
        session['rest_user']['authorization'] = digester.hexdigest()
        response.set_cookie('authorization',value=digester.hexdigest(),expires=False)

        return response
    else:
         return flask.jsonify({'success':False})
Exemple #12
0
 def generate_password_reset_token(self, expiration=3600):
     """
     Generate a password reset change token to email to an existing user.
     """
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'reset': self.id})
Exemple #13
0
from flask import Flask, make_response, jsonify, g
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
serializer = Serializer(app.config['SECRET_KEY'], expires_in=1800)

auth = HTTPTokenAuth(scheme='Bearer')

users = ['zhanghong', 'lulu', '冬阳']

for user in users:
    token = serializer.dumps({'username': user})
    print('Token for {}: {}\n'.format(user, token))


@auth.verify_token
def verify_token(token):
    g.user = None
    print(token)
    try:
        data = serializer.load(token)
    except:
        return False
    print(data)
    if 'username' in data:
        g.user = data['username']
        return True
    return False
Exemple #14
0
 def get_token(self, expiration=7200):
     s = Serializer(APP.config['SECRET_KEY'], expiration)
     return s.dumps({'user': self.get_id()}).decode('utf-8')
Exemple #15
0
    def generate_confirmation_token(self, expiration=604800):
        """Generate a confirmation token to email a new user."""

        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})
Exemple #16
0
 def get_reset_token(self, expires_sec=1800):
     s = Serializer(app.config['SECRET_KEY'], expires_sec)
     return s.dumps({'user_id': self.id}).decode('utf-8')
Exemple #17
0
 def generate_auth_token(self, expiration=3600):
     s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
     str = s.dumps({'id': self.id})
     return b64encode(str).decode('utf-8')
 def generate_auth_token(self, expiration=600):
     s = Serializer(secret_key, expires_in=expiration)
     return s.dumps({'id': self.id})
Exemple #19
0
 def generate_auth_token(self):
     s = Serializer(app.config['SECRET_KEY'])
     return s.dumps({'id': self.id})
Exemple #20
0
def gen_auth_token(user: User, expiration):
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'id': user.id})
Exemple #21
0
def create_token(uid):
    """生成token:uid, 有效期,密钥"""
    s = Serializer(current_app.config["SECRET_KEY"],
                   current_app.config["EXPIRES_IN"])
    token = s.dumps({"uid": uid}).decode("ascii")
    return token
Exemple #22
0
 def generate_token(self, expiration=600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'id': self.id}).decode('utf-8')
Exemple #23
0
 def generate_reset_token(self,expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'reset': self.username})
Exemple #24
0
def generate_auth_token(uid, ac_type, scope=None, expiration=7200):
    '''生成令牌'''
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'uid': uid, 'type': ac_type.value, 'scope': scope})
Exemple #25
0
 def generate_confirmation_token(self,
                                 expiration=86400):  # default is 24 hrs
     s = Serializer(sk, expiration)
     return s.dumps({'confirm': self.id}).decode('utf-8')
Exemple #26
0
 def generate_token(username, expiration=None):
     if expiration is None:
         expiration = default_expiration
     s = Serializer(SECRET_KEY, expires_in=expiration)
     token = s.dumps({'login': username})
     return token
Exemple #27
0
 def __init__(self, secret, backend, crypter):
     Serializer.__init__(self, secret)
     self.backend = backend
     self.crypter = crypter
Exemple #28
0
 def token(self, expiration=900):  # GENERAR TOKEN CON EXPIRACIÓN DE 900s.
     s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'id': self.id})
Exemple #29
0
 def get_reset_token(self, expires_seconds=1800):
     from run import app
     from flask import flash
     flash(self.id)
     s = Serializer(app.secret_key, expires_seconds)
     return s.dump({'id':self.id}).decode('utf-8')
Exemple #30
0
 def get_reset_token(self, expire_lim=1800):
     s = Serializer(
         secret_key=current_app.config['SECRET_KEY'], expires_in=expire_lim)
     return s.dumps({'user_id': self.id}).decode('utf-8')
Exemple #31
0
 def generate_token_for(user,expiration=100):
     if user == None: return None
     serializer = Serializer(SECURITY_PASSWORD_SALT)
     token = serializer.dumps({"username":str(user.username),'id':str(user.id)}).decode('utf-8')
     return token
Exemple #32
0
from config.config import Config

from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, \
    BadSignature, SignatureExpired

blueprints = ['app.api:route_api']

app = Flask(__name__)
app.config.from_object(Config)
CORS(app, resources=r'/*')
db = SQLAlchemy(app)
migrate = Migrate(app, db)

auth = HTTPTokenAuth(scheme='Bearer')
serializer = Serializer(app.config["SECRET_KEY"], expires_in=3600)


def create_token(data):
    """生成token"""
    token = serializer.dumps(data)
    return token.decode("utf-8")


@auth.verify_token
def verify_token(token):
    """验证token"""
    # 待完善。
    try:
        data = serializer.loads(token)
        print(data)
Exemple #33
0
def generate_auth_token(user_id, expiration=600000):
    s = Serializer(_SECRET_KEY, expires_in=expiration)
    return s.dumps({"id": user_id})
 def generate_auth_token(self):
     serializer = Serializer(SECRET_KEY)
     return serializer.dumps({'id': self.id})
Exemple #35
0
 def generar_auth_token(user=None, expiration=60 * 10):
     secrey_key = settings.SECRET_KEY
     s = Serializer(secrey_key, expires_in=expiration)
     data = {c: user.__getattribute__(c) for c in Cliente.FILD_SIGNATURE}
     return s.dumps({"cliente": data})
Exemple #36
0
 def generate_auth_token(self, expiration=40000):
     """To generate auth token."""
     s = Serializer(os.environ['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'id': self.id})
Exemple #37
0
 def generate_email_change_token(self, new_email, expiration=3600):
     """Generate an email change token to email an existing user."""
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'change_email': self.id, 'new_email': new_email})
Exemple #38
0
 def get_reset_token(self, expires_sec=1800):
     s = Serializer(app.config["SECRET_KEY"], expires_sec)
     return s.dumps({"user_id": self.id}).decode("utf-8")
Exemple #39
0
 def generate_confirmation_token(self, expiration=3600):
     s = Serializer((current_app.config["SECRET_KEY"], expiration))
     return s.dumps({"confirm": self.id})
 def generate_reset_token(self, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'reset': self.id.__str__()}).decode('utf-8')
Exemple #41
0
 def generate_auth_token(self, expiration):
     s = Serializer(current_app.config['SECRET_KEY'])
     return s.dumps({'id': self.id})
Exemple #42
0
 def generate_auth_token(self, secret_key,expiration=3600000):
     s = Serializer(secret_key, expires_in=expiration)
     print 'self.id =',self.id
     self.sessionToken=s.dumps(str(self.id))
     print 'self sessionToken=',self.sessionToken
Exemple #43
0
def main():
    """Primary CLI application logic."""
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:v", ["help",
                                                         "dservers=",
                                                         "dqueue=",
                                                         "secret=",
                                                         "bserver=",
                                                         "hserver=",
                                                         "rserver=",
                                                         "rchannel=",
                                                         "bfiltername=",
                                                         "hllname=",
                                                         "mode=",
                                                         "sleep="])
    except getopt.GetoptError as err:
        print(str(err))
        usage()
        sys.exit()

    modes = ("generate", "listen", "check", "adaptive", "initialize", "subscriber")

    # set defaults
    mode = None
    dservers = "localhost:7712,localhost:7711"
    dqueue = "objbomber"
    secret = "coolsecretbro"
    bserver = "localhost:8673"
    hserver = "localhost:4553"
    rserver = "localhost:6379"
    rchannel = "objbomber"
    bfiltername = "objbomber"
    hllname = "objbomber"
    sleep = None
    userhomedir = os.path.expanduser("~")

    # flippin' switches...
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("--dservers"):
            dservers = a
        elif o in ("--queue"):
            dqueue = [a]
        elif o in ("--secret"):
            secret = a
        elif o in ("--bserver"):
            bserver = a
        elif o in ("--hserver"):
            hserver = a
        elif o in ("--rserver"):
            rserver = a
        elif o in ("--rchannel"):
            rchannel = a
        elif o in ("--bfiltername"):
            bfiltername = a
        elif o in ("--hllname"):
            hllname = a
        elif o in ("--mode"):
            if a in modes:
                mode = a
            else:
                usage()
                sys.exit()
        elif o in ("--listen"):
            mode_listen = True
        elif o in ("--check"):
            mode_check = True
        elif o in ("--sleep"):
            sleep = int(a)
        else:
            assert False, "unhandled option"

    checkdqueue = dqueue + ".check"

    if sleep in (None, 0):
        sleep = 0.0001

    # mode must be set
    if not mode:
        usage()
        sys.exit()

    # Handler for the cryptographic signatures
    # TODO: secret should be "secret" + a version number
    s = Serializer(secret)

    # config basics
    datadir = userhomedir + "/.objbomber"

    # prepare servers and queue lists
    dservers = dservers.split(",")
    bserver = [bserver]
    hserver = hserver

    # all modes use Disque
    logging.info("Connecting to Disque...")
    disque_client = Client(dservers)
    disque_client.connect()

    if mode in ("check", "listen"):
        logging.info("Creating Bloomd Client...")
        bloomd_client = BloomdClient(bserver)
        bfilter = bloomd_client.create_filter(bfiltername)

        # add pyhlld
        logging.info("Creating HLLD Client... - not yet used")
        hlld_client = HlldClient(hserver)
        hll = hlld_client.create_set(hllname)

    if mode in ("check", "listen", "generate", "subscriber"):
        # add redis hll & pubsub
        logging.info("Creating Redis Client...")
        rhost, rport = rserver.split(":")
        redd = redis.StrictRedis(host=rhost, port=rport, db=0)
        redpubsub = redd.pubsub()

    if mode in ("subscriber"):
        redpubsub.subscribe(rchannel)

    if mode in ("generate"):
        # TODO: check on how well LevelDB handles
        #       multiple clients
        db = leveldb.LevelDB(datadir + '/notary')

    # special mode to handle our first run
    # TODO: push into a function
    # TODO: handle filesystem errors
    # TODO: reconsider using Cement for all of this
    # TODO: generate an instance GUID
    if mode == "initialize":

        UUID = uuid.uuid4()
        logging.info("Our system UUID is now: %s" % UUID)
        # TODO: save and load this uuid

        # check to see if there is a ~/.objbomber directory, quit if there is
        # TODO: this does not handle errors in initalization
        logging.info("Checking for .objbomber in %s..." % userhomedir)
        if os.path.exists(datadir):
            logging.info("Already been initialized!")
            # TODO: print some information about how to handle this
            sys.exit()

        # TODO: make one
        os.mkdir(datadir, 0700)

        # generate our RSA signing key
        # TODO: make # of bits in key a flag
        logging.info("Begining to create our notary key.")
        logging.info("Reading from RNG.")
        rng = Random.new().read

        logging.info("Generating RSA key...")
        privRSAkey = RSA.generate(4096, rng)
        privPEM = privRSAkey.exportKey()
        pubRSAkey = privRSAkey.publickey()
        pubPEM = pubRSAkey.exportKey()
        logging.info("Key generated.")

        # save privkey to disk
        with open(datadir + "/privkey.pem", "w") as keyfile:
            keyfile.write(privPEM)
            keyfile.close()
            os.chmod(datadir + "/privkey.pem", 0700)
            logging.info("Unencrypted RSA key written to disk.") 

        # save the pubkey
        with open(datadir + "/pubkey.pem", "w") as keyfile:
            keyfile.write(pubPEM)
            keyfile.close()
            logging.info("Public RSA key written to disk.")

        logging.info("Creating crypto notary storage.")
        leveldb.LevelDB(datadir + '/notary')

        # we absolutely must quit here, or we will get stuck in
        # an infinate loop
        sys.exit()

    # load our secret key (TODO: this is probably better as try/exc)
    # and build our contexts
    with open(datadir + "/privkey.pem", "r") as keyfile:
        privRSAkey = RSA.importKey(keyfile.read())

    while True:
        # TODO: Adaptive Mode - this mode should peek the queues, and
        # make a decision about where this thread can make the most
        # impact on its own.
        if mode == "adaptive":

            # TODO: Do some queue peeking.

            # TODO: Make some decisions about which mode to adapt to.

            pass

        # TODO: All modes should be placed into functions.

        # Listen Mode - Listens to the queue, pulls out jobs,
        #   validates the signature, puts them in bloomd
        if mode == "listen":
            logging.info("Getting Jobs from Disque.")
            jobs = disque_client.get_job([dqueue])

            print("Got %d jobs." % len(jobs))

            for queue_name, job_id, job in jobs:
                logging.debug("Handling a job: %s" % job)

                try:
                    job = s.loads(job)
                    logging.debug("Job Authenticated: %s" % job)
                except:
                    logging.warning("Job did not pass authentication.")
                    disque_client.nack_job(job_id)

                # add to bloom filter
                try:
                    bfilter.add(job)
                except:
                    logging.warning("Job was not added to bloomd.")
                    disque_client.nack_job(job_id)

                try:
                    hllResponse = hll.add(job)
                except:
                    logging.warning("Job was not added to hlld.")
                    disque_client.nack_job(job_id)

                # TODO: add redis HLL support

                # tell disque that this job has been processed
                disque_client.ack_job(job_id)

                # sign the check job
                job = s.dumps(job)

                # throw this message on the check queue
                disque_client.add_job(checkdqueue, job)

        elif mode == "check":
            # TODO
            # Check the secondary disque queue for checks
            # Ask the bloom filter if they have seen this

            logging.info("Getting Jobs from Disque.")
            jobs = disque_client.get_job([checkdqueue])

            for queue_name, job_id, job in jobs:
                logging.debug("Checking: %s" % job)

                try:
                    job = s.loads(job)
                except:
                    disque_client.nack_job(job_id)

                # we don't NACK on failed cache hits

                if job in bfilter:
                    logging.info("Confirming: %s" % job)
                else:
                    logging.info("Not found in bloom filter: %s" % job)

                disque_client.ack_job(job_id)

        elif mode == "generate":
            # TODO - where will these messages come from?
            # for now they will just be random numbers, but
            # really we should make them objects to really be
            # testing serialization
            msg = [random.randint(1000, 1000000),
                   random.randint(1000, 1000000)]

            # itsdangerous serialization & signing
            msg = s.dumps(msg)

            # Now that this message is serialized, we can sign it again with a
            # public key.
            # TODO: incorporate saving the signature into the notary records
            msghash = SHA.new(msg)
            signer = PKCS1_v1_5.new(privRSAkey)
            signature = signer.sign(msghash)
            assert signer.verify(msghash, signature)

            record = {'message': msg, 'signature': signature}
            record = pickle.dumps(record)

            # send the job over to Disque
            # TODO: add more command line flags for queuing
            job_id = disque_client.add_job(dqueue, msg)
            logging.debug("Added a job to Disque: %s" % msg)

            # publish just the signature on redis pubsub
            redd.publish(rchannel, signature)

            # TODO: save the publication in the notary
            # TODO: do more then just save the signatures
            # TODO: add a GUID to the key
            key = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")
            db.Put(key, record)

            # testing the results of leveldb's store, this is a test, and
            # an expensive test
            sig2 = db.Get(key)
            sig2 = pickle.loads(sig2)['signature']
            assert signer.verify(msghash, sig2)

        elif mode == "subscriber":
            msg = redpubsub.get_message()
            # TODO: do something useful, like log
            if msg:
                print("got a message")

        time.sleep(sleep)
Exemple #44
0
 def get_reset_token(self, expiration_time=1800):
     s = Serializer(current_app.config['SECRET_KEY'], expiration_time)
     return s.dumps({'user_id': self.id}).decode('utf-8')
Exemple #45
0
 def generate_email_change_token(self, new_email, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'change_email': self.id, 'new_email': new_email})
Exemple #46
0
def generate_token(user, operation, expire_in=None, **kwargs):
	s = Serializer(current_app.config["SECRET_KEY"], expire_in)

	data = {"id":user.id, "operation": operation}
	data.update(**kwargs)
	return s.dumps(data)  # 这个dumps是Serializer对象的内置方法
Exemple #47
0
 def generate_auth_token(self, expiration):
     s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'id': self.id})
Exemple #48
0
 def generate_confirmation_token(self, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'confirm': self.id})
Exemple #49
0

class User(Base):
	__tablename__ = 'users'

	id = Column(Integer, primary_key=True)
	name = Column(String(100))
	password = Column(String(500))
	salt = Column(String(100))


user = session.query(User).filter_by(name="Josh").first()

salt = user.salt

signer = Serializer(secretKey, salt=salt)

passwordOld = "super new car"
password = "******"

passwd = signer.dumps(password).split(".")[1]

oldPass = user.password

if signer.loads("\"" + passwordOld + "\"." + oldPass):
	print True

	user.password = passwd

session.commit()
Exemple #50
0
 def generate_auth_token(self, expires=3600):
     serializer = Serializer(config.SECRET_KEY, expires_in=expires)
     return serializer.dumps({'id': self.id})