def add_user(cls, account=None, passwd=None): app.logger.debug("add user start:[%s,%s]" % (account, passwd)) # check if account has register result_find = user_collection.find_one({'account': account}) if result_find: db_passwd_hash = result_find.get('passwd_hash') user_id = result_find.get('_id') s = Serializer(app.config['SECRET_KEY'], expires_in=6000) # 3600000=41 days token = s.dumps({'user_id': '%s' % user_id, 'passwd': db_passwd_hash}) app.logger.debug("user exsit [account:%s]:[user_id:%s]:[%s]\n" % (account, user_id, token)) return token, str(user_id) # generate token user_id = str(redis_db.incr(CURRENT_USER_ID)) s = Serializer(app.config['SECRET_KEY'], expires_in=6000) # 3600000=41 days token = s.dumps({'user_id': '%s' % user_id, 'passwd': passwd}) # save account/passwd to mongodb passwd_hash = pwd_context.encrypt(passwd) one_user = {'_id': user_id, 'account': account, 'passwd_hash': passwd_hash} # user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id # save token to redis redis_db.set(str(user_id), token) # save user to easemob platform im_obj.register_user(user_id, user_id) app.logger.debug("add user [%s]:[%s]:[%s]:%s]" % (account, passwd_hash, token, user_id)) return token, str(user_id)
def generate_auth_token(self, expiration = 600): s = Serializer(secret_key, expires_in=expiration) print ("secret key = ", secret_key) print ("dumps = ", s.dumps({"id": self.id})) serializedData = s.dumps({"id": self.id}) print ("dumps = ", s.loads(serializedData)) return s.dumps({"id": self.id})
def generate_confirm_token(self, expiration=3600): """ Generates a confirmation token :param expiration: time to expire :return: confirmation token """ serializer = Serializer(current_app.config["SECRET_KEY"], expires_in=expiration) self.email_confirmation_token = serializer.dumps({"confirm": self.id}) return serializer.dumps({"confirm": self.id})
def generate_access_token(self, expiration=3600): """ 生成用于 API 访问的Access_token :param expiration: Access_token 过期时间 :return: 包含Access_token的字典 """ s1 = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) s2 = Serializer(current_app.config['SECRET_KEY'], expires_in=3600*24*10) access_token = s1.dumps({'token_uid': self.user_id, 'token_usage': 'access'}).decode('ascii') refresh_token = s2.dumps({'token_uid': self.user_id, 'token_usage': 'refresh'}).decode('ascii') return dict(access_token=access_token, refresh_token=refresh_token, expires_in=expiration, expires_at=int(time.time())+expiration, token_type='Bearer')
def get_token(user_id=None): from itsdangerous import TimedJSONWebSignatureSerializer as Serializer expiration = int(current_app.permanent_session_lifetime.total_seconds()) s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) if user_id is None: token = s.dumps({'token': str(current_user.id)}) else: token = s.dumps({'token': str(user_id)}) return token
def generate_token(self, expiration=0): """Generate a timed and serialized JsonWebToken :param expiration: Token expiration time (in seconds) """ if expiration: serializer = TimedJSONWebSignatureSerializer( current_app.config['SECRET_KEY'], expiration) token = serializer.dumps({'project_id': self.id}).decode('utf-8') else: serializer = URLSafeSerializer(current_app.config['SECRET_KEY']) token = serializer.dumps({'project_id': self.id}) return token
def generate_reset_token(self, expiration=3600): """generate_reset_token:重置token信息 :param expiration: """ s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id})
def generate_confirmation_token(self, expiration=3600): """ # 生成一个令牌,有效期默认是一个小时, 令牌是个名值对,名字是confirm,值是根据id生成的。 """ s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id})
def generate_token(user, expiration=TWO_WEEKS): s = Serializer(app.config['SECRET_KEY'], expires_in=expiration) token = s.dumps({ 'id': user.id, 'email': user.email, }).decode('utf-8') return token
def generate_confirmation_token(self, expiration=3600): """generate_confirmation_token:生成token :param expiration: """ s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id})
def generate_auth_token(self, expiration): """generate a token""" s = Serializer( current_app.config['SECRET_KEY'], expiration ) return s.dumps({'id': self.id})
def generate_auth_token(self, expiration=3600): """ generate an authorization token used for API accesss """ s = Serializer( current_app.config.get('SECRET_KEY'), expires_in=expiration) return s.dumps(str(self.id))
def generate_auth_token(self, expiration): """ 生成验证token:验证字段id """ s = Serializer( current_app.config["SECRET_KEY"], expiration ) return s.dumps({'id': self.id}).decode('ascii')
def generate_active_token(self): """生成激活令牌""" # 构建序列化器(转换工具)对象 serializer = Serializer(settings.SECRET_KEY, 3600) # 转换参数 token = serializer.dumps({"confirm": self.id}) # 返回bytes类型 return token.decode()
def generate_reset_token(self, expiration=86400): """Generate a token for resetting a password :param int expiration: Time (seconds) after which token doesn't work""" s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id})
def test_make_token_auth(self): user = self.us.create(u'warlock', u'*****@*****.**', u'qwerty') s = TokenSerializer(config.SECRET_KEY, expires_in=config.SESSION_EXPIRES) token = s.dumps({u'login': user[u'login']}) self.assertEqual(token, self.us.make_auth_token(user), u'Tokens are not equal.')
def get_auth_token(self): """ Return an authentication token for the user. The auth token uniquely identifies the user and includes the salted hash of the password, then encrypted with a Timed serializer. The token_validity_duration can be set in application configuration using TOKEN_VALIDITY_DURATION """ serializer = TimedJSONWebSignatureSerializer( current_app.secret_key, expires_in=current_app.token_validity_duration ) local_txn = None if Transaction().cursor is None: # Flask-Login can call get_auth_token outside the context # of a nereid transaction. If that is the case, launch a # new transaction here. local_txn = Transaction().start( current_app.database_name, 0, readonly=True ) self = self.__class__(self.id) try: return serializer.dumps({'id': self.id, 'password': self.password}) finally: if local_txn is not None: Transaction().stop()
def generate_auth_token(): s = Serializer(app.config['SECRET_KEY'], expires_in=3600) token = s.dumps({"id": "2"}) return token
def doShare(path): is_private = False is_public = False try: f = File.get(File.public_share_url == path) is_public = True except peewee.DoesNotExist: try: f = File.get(File.private_share_url == path) is_private = True except peewee.DoesNotExist: return jsonify(message='error'), 404 if not ((is_public and f.open_public_share) or (is_private and f.open_private_share)): return jsonify(message='error'), 404 args = request.args if 'password' in args: if args['password'] == f.private_share_password: return jsonify(message='OK') else: return jsonify(message='error'), 401 s = Serializer(app.config['SECRET_KEY']) token = s.dumps({'path': path}) payload = { 'filename': f.filename, 'folder': f.folder.name, 'openPublic': f.open_public_share, 'openPrivate': f.open_private_share, 'token': token, } return jsonify(message='OK', payload=payload)
def generate_auth_token(self, expiration=None): if expiration is None: expiration = 3600 from flask import current_app app = current_app s = Serializer(app.config['SECRET_KEY'], expires_in=int(expiration)) y = s.dumps({'uid':self.uid}) return y
def token_post(): try: if request.json is None: return jsonify({'message': 'Problems parsing JSON'}), 415 if not request.json.get('username', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return jsonify({'message': 'Validation Failed', 'errors': error}), 422 if not request.json.get('password', None): error = {'resource': 'Token', 'field': 'password', 'code': 'missing_field'} return jsonify({'message': 'Validation Failed', 'errors': error}), 422 user = Users.query.filter_by(username=request.json.get('username'), banned=0).first() if not user: return jsonify({'message': 'username or password error'}), 422 if not sha256_crypt.verify(request.json.get('password'), user.password): return jsonify({'message': 'username or password error'}), 422 s = Serializer(app.config['SECRET_KEY'], expires_in=app.config['EXPIRES']) token = s.dumps({'uid': user.id, 'scope': user.scope.split(',')}) except Exception as e: print e return jsonify({ 'uid': user.id, 'access_token': token, 'token_type': 'self', 'scope': user.scope, 'expires_in': app.config['EXPIRES'] }), 201
def generate_crypto_token(token, expires_in=600): """ Generates a cryptographically signed message as a token using itsdangerous """ s = Serializer (app.config['SECRET-KEY']) return s.dumps({'crypto_token': token}) # Returns a string
def admin_signup(admin_id, company_id, admin_email, company_email): TAG = 'admin signup' log = Logger('AdminSignUp') salt_key = environ.get('salt_key') json_url_key = environ.get('json_url_key') company_id = str(company_id) admin_id = str(admin_id) danger_signer = TimedJSONWebSignatureSerializer(json_url_key) danger_signer.expires_in = 86400 hash_url = danger_signer.dumps({'cmd_hash': company_id, 'adm_hash': admin_id}, salt=salt_key) link_url = str(environ.get('SERVER_CNAME')) + '/activation/' + hash_url message = loader.load('verification_mail.html').generate( company_name=company_email, activation_link=link_url) try: ses_conn.send_email('*****@*****.**', 'MDM Trial Activation Link', message, [admin_email], format='html') except Exception as err: log.e(TAG, "Error {0} in sending mail from ses side.".format(err))
def profile_route(): s = Serializer(secret, expires_in = 300) options = { 'token': s.dumps({ 'username': session['username'] }), 'interfaces': database.list_interfaces(session['username']) } return render_template("profile.html", **options)
class TokenAuthenticator(AbstractAuthenticationProvider): def __init__(self, secret_key, expires_in_seconds=600): self._secret_key = secret_key self._serializer = TimedJSONWebSignatureSerializer(self._secret_key, expires_in_seconds) def generate_auth_token(self): return self._serializer.dumps( {USERNAME_FIELD: rest_security.get_username()}) def authenticate(self, userstore): try: open_token = self._serializer.loads(_retrieve_token_from_request()) except SignatureExpired: raise Exception('token expired') except BadSignature: raise Exception('invalid token') username = open_token.get(USERNAME_FIELD) if not username: raise Exception('username not found in token') user = userstore.get_user(username) if not user: raise Exception('failed to authenticate user "{0}", user not found' .format(username)) return user['username']
def get_token(self): if self.test: secret_key = 'NOT_SO_SECRET_KEY' else: secret_key = '' # Get from config! s = Serializer(secret_key, expires_in = 30) return s.dumps({'username': self.username, 'type': self.type })
def generate_auth_token(self, expires_in=3600): """ Generate the authenticaton token and it is valid for 3600 seconds :param expires_in: """ s = Serializer(current_app.config['SECRET_KEY'], expires_in=expires_in) return s.dumps({'id': self.id}).decode('utf-8')
def register(): register_form = RegisterForm() data = { 'title': 'Register', 'form': register_form, } if register_form.validate_on_submit(): # get data from form username = register_form.username.data password = register_form.password.data confirm_password = register_form.confirmPassword.data email = register_form.email.data # check data if len(username) < 2: flash(u'用户名长度不能小于2!', 'danger') return redirect(url_for('register')) if password != confirm_password: flash(u'两次密码不匹配!', 'danger') return redirect(url_for('register')) if len(password) < 6: flash(u'密码长度不能小于6!', 'danger') return redirect(url_for('register')) if not re.match(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', email): flash(u'Email地址不规范!', 'danger') return redirect(url_for('register')) # Check Username is already register user = Users.query.filter_by(username=username).first() if user is not None or user: flash(u'用户名已存在!', 'danger') return redirect(url_for('register')) # Insert into database user = Users(id="", username=username, email=email, password=password) db.session.add(user) db.session.commit() user = Users.query.filter_by(username=username).first_or_404() tid = user.id users_info = UsersInfo(id="", user_id=tid, register_time="", last_login_time="", last_login_ip=request.remote_addr, token=random_str(32), is_active=0, qiniu_have_account=0, qiniu_access_key=None, qiniu_secret_key=None, qiniu_bucket_name=None, qiniu_domain=None) db.session.add(users_info) db.session.commit() session['user_id'] = tid # Send mail s = Serializer(app.config['SECRET_KEY'], 3600) token = s.dumps({'user_id': tid}) send_mail(email, ' Please confirm your account', 'mail/confirm', username=username, token=token) # return result flash(u'注册成功!请到邮箱查看验证邮件,验证通过后方可登录。', 'success') return redirect(url_for('register')) return render_template("register.html", data=data)
def token_post(): try: if request.json is None: return jsonify({'message': 'Problems parsing JSON'}), 400 if not request.json.get('username', None): error = {'resource': 'Token', 'field': 'username', 'code': 'missing_field'} return jsonify({'message': 'Validation Failed', 'errors': error}), 422 if not request.json.get('password', None): error = {'resource': 'Token', 'field': 'password', 'code': 'missing_field'} return jsonify({'message': 'Validation Failed', 'errors': error}), 422 if g.uid == -1: return jsonify({'message': 'username or password error'}), 422 s = Serializer(app.config['SECRET_KEY'], expires_in=app.config['EXPIRES']) token = s.dumps({'uid': g.uid, 'scope': g.scope.split(',')}) except Exception as e: logger.error(e) raise return jsonify({'uid': g.uid, 'access_token': token, 'token_type': 'self', 'scope': g.scope, 'expires_in': app.config['EXPIRES']}), 201, {'Cache-Control': 'no-store', 'Pragma': 'no-cache'}
def register(): form = RegistrationForm() if form.validate_on_submit(): #username,email,password,firstname,lastname,department,institution,city,country values = {'username':form.username.data, 'email':form.email.data, 'password':form.password.data, 'firstname':form.firstname.data, 'lastname':form.lastname.data, 'department':form.department.data, 'institution':form.institution.data, 'city':form.city.data, 'country':form.country.data } id = insert_new_user(values) s = Serializer(current_app.config['SECRET_KEY'], 3600) token = s.dumps({'confirm': id}) send_email(form.email.data, 'Confirm Your Account', 'auth/email/confirm', user=form.username.data, token=token) flash('A confirmation email has been sent to you by email.') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def generate_auth_token(self, expiration = 600): s = Serializer(app.config['SECRET_KEY'], expires_in = expiration) return s.dumps({ 'id': self.id })
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})
def generate_auth_token(self, expiration=600): s = Serializer(secret_key, expires_in=expiration) return s.dumps({'id': self.id})
def generate_auth_token(self, expires=3600): serializer = Serializer(config.SECRET_KEY, expires_in=expires) return serializer.dumps({'id': self.id})
def get_reset_token(self, expires_sec=1800): s = Serializer(app.secret_key, expires_sec) return s.dumps({'_id': str(self.id)}).decode('utf-8')
def generate_reset_token(self, expiration=3600): serializer = TimedJSONWebSignatureSerializer( current_app.config['SECRET_KEY'], expiration) return serializer.dumps({'reset': self.username})
def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('ascii')
def generate_token(self, expiration=600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'id': self.id}).decode('utf-8')
def generate_api_token(self, expiration: int) -> str: s = TimedJSONWebSignatureSerializer( current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('ascii') # type:ignore
def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id})
def generate_auth_token(self, expiration=600): """Genrate auth token to be used instead of password.""" s = Serializer(secret_key, expires_in=expiration) return s.dumps({'id': self.id})
def generate_user_token(self): s = Serializer('SECRET_KEY') self.token = s.dumps({'token': self.stuId}).decode('ascii') return self.token
def generate_reset_token(self, expiration=3600): # 生成重设密码连接token,过期时间为3600秒,self.id为用户id s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id})
def generate_confirmation_token(self, expiration=48 * 60 * 60): #有效期48小时 s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirmed': self.id})
def generate_auth_token(self): serializer = Serializer(current_app.config["SECRET_KEY"], 3600) # Token expires in one hour return serializer.dumps({"token": self.id})
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer s = Serializer(secret_key='123', expires_in=3600) data = {'openid': 'abc123'} s.dumps(data)
def get_reset_token(self, expires_sec=900): # returns the token with a payload and an exipartion time limit (defaulting to 15 minutes) s = Serializer(current_app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8')
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)
def share(path): is_public = False is_private = False try: f = File.get(File.public_share_url == path) is_public = True except peewee.DoesNotExist: try: f = File.get(File.private_share_url == path) is_private = True except peewee.DoesNotExist: return jsonify(message='error'), 404 actual_filename = generate_filename(f.folder.name, f.filename) target_file = os.path.join(os.path.expanduser(app.config['UPLOAD_FOLDER']), actual_filename) if not ((is_public and f.open_public_share) or (is_private and f.open_private_share)): return jsonify(mesage='error'), 404 s = URLSafeSerializer(app.config['SECRET_KEY'], expires_in=24 * 3600) args = request.args if args.get('download') == 'true': # print('TOKEN1:', request.cookies['token']) token = None cookies = request.cookies if 'token' in cookies: token = cookies['token'] # print(token) try: data = s.loads(token) if data['path'] == path: if os.path.exists(target_file): return send_file(target_file) else: return jsonify(message='error'), 404 else: return jsonify(message='unauthorized'), 401 except: return jsonify(message='unauthorized'), 401 else: return jsonify(message='error'), 401 token = s.dumps({'path': path}).decode('utf-8') payload = { 'filename': f.filename, 'folder': f.folder.name, 'open_public_share': f.open_public_share, 'open_private_share': f.open_private_share, 'token': token, } if is_private: if 'password' not in args or args[ 'password'] != f.private_share_password: payload['token'] = '' return jsonify(message='OK', data=payload)
def get_reset_token(self, expires_time=1800): s = Serializer(app.config['SECRET_KEY'], expires_time) return s.dumps({'user_id': self.id}).decode('utf-8')
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 gen_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps(bson_to_json({"id": self.id}))
def generate_verify_email_url(user): s = Serializer(SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES) data = {'user_id': user.id, 'email': user.email} token = s.dumps(data) return settings.EMAIL_VERIFY_URL + '?token=' + token.decode()
def generate_auth_token(self, expiration=1200): print("making a token for", self.name) s = Serializer(app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id, 'name': self.name})
def generate_activate_token(self, expires_in=3600): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expires_in) return s.dumps({'id': self.id})
def generate_auth_token(self, expiration=6000): s = TimedJSONWebSignatureSerializer(secret_key, expires_in=expiration) token = s.dumps({'id': self.id}) return token
def generate_confirmation_token(self, expiration=3600): """ generate the token for user. """ s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id})
def _read(self, ti, try_number, metadata=None): """ Template method that contains custom logic of reading logs given the try_number. :param ti: task instance record :param try_number: current try_number to read log from :param metadata: log metadata, can be used for steaming log reading and auto-tailing. :return: log message as a string and metadata. """ # Task instance here might be different from task instance when # initializing the handler. Thus explicitly getting log location # is needed to get correct log path. log_relative_path = self._render_filename(ti, try_number) location = os.path.join(self.local_base, log_relative_path) log = "" if os.path.exists(location): try: with open(location, encoding="utf-8", errors="surrogateescape") as file: log += f"*** Reading local file: {location}\n" log += "".join(file.readlines()) except Exception as e: log = f"*** Failed to load local log file: {location}\n" log += f"*** {str(e)}\n" elif conf.get('core', 'executor') == 'KubernetesExecutor': try: from airflow.kubernetes.kube_client import get_kube_client kube_client = get_kube_client() if len(ti.hostname) >= 63: # Kubernetes takes the pod name and truncates it for the hostname. This truncated hostname # is returned for the fqdn to comply with the 63 character limit imposed by DNS standards # on any label of a FQDN. pod_list = kube_client.list_namespaced_pod(conf.get('kubernetes', 'namespace')) matches = [ pod.metadata.name for pod in pod_list.items if pod.metadata.name.startswith(ti.hostname) ] if len(matches) == 1: if len(matches[0]) > len(ti.hostname): ti.hostname = matches[0] log += f'*** Trying to get logs (last 100 lines) from worker pod {ti.hostname} ***\n\n' res = kube_client.read_namespaced_pod_log( name=ti.hostname, namespace=conf.get('kubernetes', 'namespace'), container='base', follow=False, tail_lines=100, _preload_content=False, ) for line in res: log += line.decode() except Exception as f: log += f'*** Unable to fetch logs from worker pod {ti.hostname} ***\n{str(f)}\n\n' else: url = os.path.join("http://{ti.hostname}:{worker_log_server_port}/log", log_relative_path).format( ti=ti, worker_log_server_port=conf.get('logging', 'WORKER_LOG_SERVER_PORT') ) log += f"*** Log file does not exist: {location}\n" log += f"*** Fetching from: {url}\n" try: timeout = None # No timeout try: timeout = conf.getint('webserver', 'log_fetch_timeout_sec') except (AirflowConfigException, ValueError): pass signer = TimedJSONWebSignatureSerializer( secret_key=conf.get('webserver', 'secret_key'), algorithm_name='HS512', expires_in=conf.getint('webserver', 'log_request_clock_grace', fallback=30), # This isn't really a "salt", more of a signing context salt='task-instance-logs', ) response = httpx.get( url, timeout=timeout, headers={'Authorization': signer.dumps(log_relative_path)} ) response.encoding = "utf-8" if response.status_code == 403: log += ( "*** !!!! Please make sure that all your Airflow components (e.g. " "schedulers, webservers and workers) have" " the same 'secret_key' configured in 'webserver' section !!!!!\n***" ) log += ( "*** See more at https://airflow.apache.org/docs/apache-airflow/" "stable/configurations-ref.html#secret-key\n***" ) # Check if the resource was properly fetched response.raise_for_status() log += '\n' + response.text except Exception as e: log += f"*** Failed to fetch log file from worker. {str(e)}\n" return log, {'end_of_log': True}
def get_reset_token(self, expires_sec=1200): s = Serializer(current_app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8')
def generate_auth_token(self, expiration): """ To generate authentication via rest """ s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.email})