def on_message(self, message): if message.startswith("{"): msg = None try: json_message = json.loads(message) except Exception as e: return self.write_message("JSON ERROR") else: id_user = None if "phanterpwa-authorization" in json_message and "message" in json_message: msg = json_message["message"] if json_message["phanterpwa-authorization"] is not "anonymous": t = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_user_token_expire'] ) token_content = None try: token_content = t.loads(json_message['phanterpwa-authorization']) except BadSignature: token_content = None except SignatureExpired: token_content = None if token_content and 'id' in token_content: id_user = token_content['id'] if id_user: q_user = self.DALDatabase(self.DALDatabase.auth_user.id == id_user).select().first() if q_user: self.phanterpwa_current_user = q_user try: new_set = set(self._online_users[self.phanterpwa_current_user.id]) except KeyError: new_set = set([self]) for con in new_set: if not con.ws_connection: new_set.remove(con) new_set.add(self) self._online_users[self.phanterpwa_current_user.id] = new_set if msg == "command_online": print("{0} webSocket opened".format(self.phanterpwa_current_user.email)) self.write_message(u"__ You're online") return if message[:17] == "check_compilation": r = check_compilation.findall(message) if r: app_compilation = r[0] if str(self.projectConfig['PROJECT']['compilation']) == app_compilation: self.write_message("Compilation: {0}".format(app_compilation)) else: self.write_message("reload") else: self.write_message(u"You said: " + message) for con in self.get_connections(): print("usuario:", id(con)) con.write_message( "O usuário {0} falou: {1}".format(id(self), message) )
def verify_reset_token(token): s = Serialize(current_app.config['SECRET_KEY']) # we could have errors when token expire so we use try try: user_id = s.loads(token)['user_id'] except: return None return User.query.get(user_id)
def __init__(self, _id, secret_key, time_token_expire, num_opt=4, question="Which figure below corresponds to: {option}.", debug=False, translator=None): super(Captcha, self).__init__() self.debug = debug self.secret_key = secret_key self.time_token_expire = time_token_expire self.serializer = Serialize( self.secret_key, self.time_token_expire ) self._background_color = { "red": "#990000", "yellow": "#FFCC00", "blue": "#6699FF" } self._foreground_color = { "black": "#1F1A17", "white": "white", "green": "#009933" } self._signature = None self._choice = None self.translator = translator self.color_pairs = dict() self.options = dict() self._opt = [] self.recipes = dict() self.classification = set() self.vectors = dict() self.grafical_forms = dict() self.svg_forms = dict() self.question = question if isinstance(_id, str): self._id = _id else: raise ValueError("The captcha id must be string. Given: {0}".format(type(_id))) self.num_opt = num_opt self.keys_attributes = [] self.keys_lines_cols = [] if self.debug or not os.path.exists(os.path.join(__dirname__, "captchadata.json")): self._combine_colors() self._recipes() self._vectors() self._svgs() else: with open(os.path.join(__dirname__, "captchadata.json"), "r", encoding="utf-8") as f: captchadata = json.load(f) self.options = captchadata[0] self.grafical_forms = captchadata[1]
def get(self, *args, **kargs): """ Receive request to create and response with a token csrf or captcha """ form_identify = args[0] list_forms = self.list_forms id_client = int(self.phanterpwa_client_token_checked["id_client"]) if form_identify in list_forms: self.DALDatabase((self.DALDatabase.csrf.client == id_client) & (self.DALDatabase.csrf.form_identify == form_identify)).delete() t = Serialize( "csrf-{0}".format(self.projectConfig['BACKEND'][self.app_name] ['secret_key']), self.projectConfig['BACKEND'][ self.app_name]['default_time_csrf_token_expire']) id_csrf = self.DALDatabase.csrf.insert( form_identify=form_identify, user_agent=self.phanterpwa_user_agent, ip=self.phanterpwa_remote_ip, client=id_client) if id_csrf: sign_captha = t.dumps({ 'id': str(id_csrf), 'form_identify': form_identify, 'user_agent': self.phanterpwa_user_agent, 'ip': self.phanterpwa_remote_ip, 'user': self.phanterpwa_current_user.id }) sign_captha = sign_captha.decode("utf-8") q_csrf = self.DALDatabase( self.DALDatabase.csrf.id == id_csrf).select().first() q_csrf.update_record(token=sign_captha) msg = "Form signed" self.DALDatabase.commit() self.set_status(200) return self.write({ "status": "OK", "code": 200, "message": msg, "i18n": { "message": self.T(msg) }, "csrf": sign_captha }) self.DALDatabase.commit() msg = "The form can't sign" self.set_status(400) return self.write({ "status": "Bad Request", "code": 400, "message": msg, "i18n": { "message": self.T(msg) } })
def post(self, request): # 进行注册处理 # 获取信息 username = request.POST.get('user_name') password = request.POST.get('pwd') email = request.POST.get('email') allow = request.POST.get('allow') print(username) # 数据校验 if not all([username, password, email]): return render(request, 'register.html', {'errmsg': '信息输入不完整'}) if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return render(request, 'register.html', {'errmsg': '邮箱格式不正确'}) if allow != 'on': return render(request, 'register.html', {'errmsg': '请勾选同意'}) # 检验用户名是否重复 try: user = User.objects.get(username=username) except User.DoesNotExist: # 用户名不存在 user = None if user: return render(request, 'register.html', {'errmsg': '用户已存在'}) # 业务处理 :用户注册 user = User.objects.create_user(username, email, password) user.is_active = 0 user.save() # user =User() # user.username = username # user.password = password # user.email =email # user.save() # 发送激活邮件,包含激活链接:https://127.0.0.1:8000/user/active/1 # 激活邮件中需要包含用户的身份信息,并且把身份信息加密 # 加密用户信息,生成激活token serialize = Serialize(settings.SECRET_KEY, 3600) info = {'confirm': user.id} token = serialize.dumps(info) # byte token = token.decode('utf-8') # # 发邮件1 send_register_active_email.delay(email, username, token) # 发出任务 # 发邮件2 # subject = '天天生鲜欢迎信息' # message = '' # sender = settings.EMAIL_FROM # receiver = [email] # html_message = '<h1>%s,欢迎注册天天生鲜会员</h1>请点击以下链接激活您的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' %(username, token, token) # send_mail(subject, message, sender, receiver, html_message=html_message) # # 返回应答,跳转首页 return redirect(reverse('goods:index'))
def rest_password(token, new_password, expiration=600): s = Serialize(current_app.config['SECRET_KEY'], expiration) try: data = s.loads(token.encode('utf-8')) except: return False uid = data.get('id') with db.auto_commit(): user = User.query.get(uid) user.password = new_password return True
def get(self, request, token): serialize = Serialize(settings.SECRET_KEY, 3600) try: info = serialize.loads(token) user_id = info['confirm'] user = User.objects.get(id=user_id) user.is_active = 1 user.save() except SignatureExpired as e: return HttpResponse('链接已过期') return redirect(reverse('user:login'))
def get(self,request,token): # 进行解密,获取要激活的用户信息 serializer = Serialize(settings.SECRET_KEY, 3600) # 解密 try: info = serializer.loads(token) user_id = info['confirm'] logger.info("userId=%s" % (user_id,)) user = User.objects.get(id=user_id) user.is_active = 1 user.save() # 跳转到登录页面 return redirect(reverse('user:login')) except SignatureExpired as ex: return HttpResponse('此链接激活已过期')
def post(self, *args): db = self.DALDatabase db( (db.internal_messages.senders == self.phanterpwa_current_user.id) & (db.internal_messages.subject == None) & (db.internal_messages.text_message == None) & (db.internal_messages.message_sent != True) ).delete() id_new_message = db.internal_messages.insert( senders=self.phanterpwa_current_user.id, written_on=datetime.now(), message_sent=False ) id_client = int(self.phanterpwa_client_token_checked["id_client"]) db((db.csrf.client == id_client) & (db.csrf.form_identify == "phanterpwa-form-send-messages")).delete() t = Serialize( "csrf-{0}".format(self.projectConfig['BACKEND'][self.app_name]['secret_key']), self.projectConfig['BACKEND'][self.app_name]['default_time_csrf_token_expire'] ) id_csrf = db.csrf.insert( form_identify="phanterpwa-form-send-messages", user_agent=self.phanterpwa_user_agent, ip=self.phanterpwa_remote_ip, client=id_client ) sign_csrf = t.dumps({ 'id': str(id_csrf), 'form_identify': "phanterpwa-form-send-messages", 'user_agent': self.phanterpwa_user_agent, 'ip': self.phanterpwa_remote_ip, 'user': self.phanterpwa_current_user.id }) sign_csrf = sign_csrf.decode("utf-8") q_csrf = db(db.csrf.id == id_csrf).select().first() q_csrf.update_record(token=sign_csrf) message = 'Create new message' i18nmessage = self.T(message) db.commit() self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'csrf': sign_csrf, 'id_new_message': id_new_message, 'message': message, 'i18n': {'message': i18nmessage}, })
def post(self, request): # 1. 接收数据 username = request.POST.get('user_name') password = request.POST.get('pwd') repassword = request.POST.get('cpwd') email = request.POST.get('email') allow = request.POST.get('allow') # 2. 数据校验 if not all([username, password, repassword, email]): return render(request, 'regsister.html', {'errmsg': '数据不完整'}) if password != repassword: return render(request, 'register.html', {'errmsg': '两次密码不一致'}) if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return render(request, 'register.html', {'errmsg': '邮箱格式错误'}) if allow != 'on': return render(request, 'register.html', {'errmsg': '请同意协议'}) try: user = User.objects.get(username=username) except User.DoesNotExist: user = None if user: return render(request, 'register.html', {'errmsg': '用户名已存在'}) # 3. 业务处理 user = User.objects.create_user(username, email, password) # 取消默认的账户激活 user.is_active = 0 user.save() # 加密激活信息 serialize = Serialize(settings.SECRET_KEY, 3600) info = {'confirm': user.id} token = serialize.dumps(info) token = token.decode('utf8') # 发送邮件 send_register_active_email.delay(email, username, token) # 4. 返回应答 url = reverse('goods:index') return redirect(url)
def get(self, request, token): '''进行用户激活''' # 解密,获取要激活的用户信息 serialize = Serialize(settings.SECRET_KEY, 3600) try: info = serialize.loads(token) # 获取待激活用户的id user_id = info['confirm'] # 根据id获取用户信息 user = User.objects.get(id=user_id) user.is_active = 1 user.save() # 跳转登录页面 return redirect(reverse('user:login')) except SignatureExpired as e: # 激活链接已失效 return HttpResponse('链接已失效')
def post(self, request): username = request.POST.get("user_name") password = request.POST.get("pwd") email = request.POST.get("email") allow = request.POST.get("allow") if not all([username, password, email]): return render(request, 'register.html', {'errmsg': '信息不完善!!'}) if allow != 'on': return render(request, 'register.html', {'errmsg': '请勾选协议!!'}) # 校验用户名是否存在 try: # user = models.DfUser.objects.get(user_name=username) user = User.objects.get(username=username) except User.DoesNotExist: user = None if user: # 用户名已存在 return render(request, 'register.html', {'errmsg': '用户名已存在'}) # user = models.DfUser.objects.create(user_name=username, password=password, email=email) user = User.objects.create_user(username, email, password) user.is_active = 0 user.ctime = datetime.datetime.now() user.save() # 发送激活邮件,包含激活链接: http://127.0.0.1:8000/user/active/3 # 激活链接中需要包含用户的身份信息, 并且要把身份信息进行加密 # 加密用户的身份信息,生成激活token 有效期1小时 serializer = Serialize(settings.SECRET_KEY, 3600) info = {'confirm': user.id} # 加密 token = serializer.dumps(info) token = token.decode() # bytes 转 str logger.info("token:%s" % token) # 发邮件 send_register_active_email.delay(email, username, token) return redirect(reverse('goods:index'))
def create_serialize(): return Serialize(current_app.config['SECRET_KEY'],expires_in=7200)
def generate_token(self, expiration=600): s = Serialize(current_app.config['SECRET_KEY'], expiration) temp = s.dumps({'id': self.id}).decode('utf-8') return temp
def get(self, *args, **kargs): social_name = args[0] dict_arguments = {k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments} url_base = self.projectConfig['BACKEND'][self.app_name]['http_address'] if social_name == "google": state = dict_arguments.get("state") q_state = self.DALDatabase( (self.DALDatabase.social_auth.social_name == "google") & (self.DALDatabase.social_auth.request_state == state)).select().first() origin = None if not q_state or q_state.used is True: message = "The authentication request has already been used." return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'i18n': { 'message': self.T(message) } }) else: self.phanterpwa_client_token = q_state.client_token q_state.update_record(used=True) origin = q_state.origin self.DALDatabase.commit() uri = "{0}{1}".format(url_base, self.request.uri) client_id = self.projectConfig['OAUTH_{0}'.format(social_name.upper())]['client_id'] client_secret = self.projectConfig['OAUTH_{0}'.format(social_name.upper())]['client_secret'] redirect_uri = '{0}/api/oauth/redirect/{1}'.format(url_base, social_name) scope = ['openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope) try: token = oauth.fetch_token( 'https://accounts.google.com/o/oauth2/token', authorization_response=uri, client_secret=client_secret) except Exception as e: self.logger_api.warning(e) message = "There was a problem trying to authenticate using a google account." return self.write({ 'status': 'Bad Request', 'code': 400, 'uri': uri, 'message': message, 'i18n': { 'message': self.T(message) } }) else: url_consult = self.projectConfig['OAUTH_{0}'.format(social_name.upper())]['remote_address'] googleapi = "{0}?access_token={1}".format( url_consult, quote(token['access_token'])) try: with urllib.request.urlopen(googleapi) as req: googleapi_user = req.read() googleapi_user = json.loads(googleapi_user) except Exception as e: self.logger_api.warning(e) message = "There was a problem trying to load user information on google api." self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'uri': googleapi, 'message': message, 'i18n': { 'message': self.T(message) } }) else: email_verified = googleapi_user.get("email_verified", False) if not email_verified: self.logger_api.warning( 'LOGIN BY OAUTH METHOD (EMAIL NOT VERIFIED)\n\tsocial_login: {0}\n\tname: {1}\n\temail: {2}\n\temail_verified: {3}\n\tlocale: {4}'.format( social_name, googleapi_user.get("name", False), googleapi_user.get("email", False), googleapi_user.get("email_verified", False), googleapi_user.get("locale", False), ) ) message = "The google email has not been verified." self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'google_api': googleapi_user, 'i18n': { 'message': self.T(message) } }) email = googleapi_user.get('email', None) if email: q_user = self.DALDatabase(self.DALDatabase.auth_user.email == email).select().first() if q_user: self.logger_api.info( 'LOGIN BY OAUTH METHOD\n\tsocial_login: {0}\n\tname: {1}\n\temail: {2}'.format( social_name, googleapi_user.get("name", False), googleapi_user.get("email", False) ) ) q_user.update_record(activated=True) timeout_token_user = self.projectConfig['BACKEND'][self.app_name]['default_time_user_token_expire_remember_me'] t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], timeout_token_user ) content = { 'id': str(q_user.id), 'email': email } token_user = t_user.dumps(content) token_user = token_user.decode('utf-8') q_role = self.DALDatabase( (self.DALDatabase.auth_membership.auth_user == q_user.id) & (self.DALDatabase.auth_group.id == self.DALDatabase.auth_membership.auth_group) ).select(self.DALDatabase.auth_group.role, orderby=self.DALDatabase.auth_group.grade) roles = [x.role for x in q_role] role = None if roles: role = roles[-1] q_user.update_record(login_attempts=0) t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_client_token_expire'] ) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]["secret_key"], salt="url_secret_key" ) r_client = self.DALDatabase(self.DALDatabase.client.token == self.phanterpwa_client_token).select().first() if r_client: r_client.delete_record() id_client = self.DALDatabase.client.insert(auth_user=q_user.id, date_created=datetime.now()) q_client = self.DALDatabase(self.DALDatabase.client.id == id_client).select().first() content = { 'id_user': str(q_user.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_url = t_url.dumps(content) token_client = t_client.dumps(content) token_client = token_client.decode('utf-8') q_client.update_record( token=token_client, date_created=datetime.now(), remember_me=True, locked=False, ) if not q_user.permit_mult_login: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == q_user.id) & (self.DALDatabase.client.token != token_client) ).select() if r_client: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == q_user.id) & (self.DALDatabase.client.token != token_client) ).delete() user_image = PhanterpwaGalleryUserImage(q_user.id, self.DALDatabase, self.projectConfig) social_image = googleapi_user.get("picture", None) redirect = "{0}#_phanterpwa:/oauth/{1}/{2}".format( origin if origin else self.projectConfig['BACKEND'][self.app_name]['http_address'], social_name, state ) q_state.update_record(user_credentials=json.dumps({ 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, 'auth_user': { 'id': str(q_user.id), 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'activated': True, 'image': user_image.id_image, 'social_image': social_image, 'two_factor': False, 'multiple_login': q_user.permit_mult_login, 'social_login': social_name } })) self.DALDatabase.commit() self.set_status(200) return self.write( str(HTML(HEAD(), BODY(SCRIPT("window.location = '{0}'".format(redirect)))))) else: self.logger_api.warning( 'CREATING ACCOUNT AND LOGIN BY OAUTH METHOD\n\tsocial_login: {0}\n\tname: {1}\n\temail: {2}\n\temail_verified: {3}\n\tlocale: {4}'.format( social_name, googleapi_user.get("name", False), googleapi_user.get("email", False), googleapi_user.get("email_verified", False), googleapi_user.get("locale", False), ) ) new_password = os.urandom(3).hex() password_hash = pbkdf2_sha512.hash("password{0}{1}".format( new_password, self.projectConfig['BACKEND'][self.app_name]['secret_key'])) table = self.DALDatabase.auth_user social_image = googleapi_user.get("picture", None) first_name = googleapi_user.get("given_name", "") last_name = googleapi_user.get("family_name", "") dict_arguments = { "first_name": first_name, "last_name": last_name, "email": email, "password_hash": password_hash, "activated": True } result = FieldsDALValidateDictArgs( dict_arguments, *[table[x] for x in table.fields if x in [ "first_name", "last_name", "email", "password_hash"]] ) r = result.validate_and_insert(self.DALDatabase.auth_user) if r and r.id: q_user = self.DALDatabase(self.DALDatabase.auth_user.id == r.id).select().first() id_user = q_user.id q_user.update_record(activated=True) if r.id == 1: role = "root" id_role = self.DALDatabase(self.DALDatabase.auth_group.role == 'root').select().first() if id_role: self.DALDatabase.auth_membership.insert( auth_user=1, auth_group=id_role.id ) else: role = "user" self.DALDatabase.auth_membership.insert(auth_user=r.id, auth_group=3) t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_user_token_expire'] ) content_user = { 'id': str(r.id), 'email': dict_arguments['email'] } token_user = t_user.dumps(content_user) token_user = token_user.decode('utf-8') token_client = self.phanterpwa_client_token id_client = self.DALDatabase.client.update_or_insert(auth_user=r.id) t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_client_token_expire'] ) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]["secret_key"], salt="url_secret_key" ) content_client = { 'id_user': str(r.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_url = t_url.dumps(content_client) token_client = t_client.dumps(content_client) token_client = token_client.decode('utf-8') q_client = self.DALDatabase(self.DALDatabase.client.id == id_client).select().first() q_client.update_record( token=token_client, date_created=datetime.now() ) r_client = self.DALDatabase(self.DALDatabase.client.token == self.phanterpwa_client_token).select().first() if r_client: r_client.delete_record() if not q_user.permit_mult_login: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token != self.phanterpwa_client_token) ).select() if r_client: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token != self.phanterpwa_client_token) ).remove() user_image = PhanterpwaGalleryUserImage(r.id, self.DALDatabase, self.projectConfig) self.set_status(201) roles = ["user"] role = "user" redirect = "{0}#_phanterpwa:/oauth/{1}/{2}".format( origin if origin else self.projectConfig['BACKEND'][self.app_name]['http_address'], social_name, state ) q_state.update_record(user_credentials=json.dumps({ 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, 'auth_user': { 'id': str(q_user.id), 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'activated': True, 'image': user_image.id_image, 'social_image': social_image, 'two_factor': False, 'multiple_login': q_user.permit_mult_login, 'social_login': social_name } })) self.DALDatabase.commit() return self.write( str(HTML(HEAD(), BODY(SCRIPT("window.location = '{0}'".format(redirect)))))) elif social_name == "facebook": state = dict_arguments.get("state") q_state = self.DALDatabase( (self.DALDatabase.social_auth.social_name == "facebook") & (self.DALDatabase.social_auth.request_state == state)).select().first() origin = None if not q_state: message = "The authentication request has already been used." return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'i18n': { 'message': self.T(message) } }) else: self.phanterpwa_client_token = q_state.client_token origin = q_state.origin q_state.delete_record() self.DALDatabase.commit() uri = "{0}{1}".format(url_base, self.request.uri) client_id = self.projectConfig['OAUTH_{0}'.format(social_name.upper())]['client_id'] client_secret = self.projectConfig['OAUTH_{0}'.format(social_name.upper())]['client_secret'] redirect_uri = '{0}/api/oauth/redirect/{1}'.format(url_base, social_name) oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope='email') try: token = oauth.fetch_token( 'https://graph.facebook.com/oauth/access_token', authorization_response=uri, client_secret=client_secret) except Exception as e: self.logger_api.warning(e) message = "There was a problem trying to authenticate using a facebook account." return self.write({ 'status': 'Bad Request', 'code': 400, 'uri': uri, 'message': message, 'i18n': { 'message': self.T(message) } }) else: try: facebook_user = oauth.get( 'https://graph.facebook.com/me?fields=name,first_name,last_name,email,picture') facebookapi_user = json.loads(facebook_user.content) except Exception as e: self.logger_api.warning(e) message = "There was a problem trying to load user information on facebook api." self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'i18n': { 'message': self.T(message) } }) else: email = facebookapi_user.get('email', None) social_image = None try: social_image = facebookapi_user["picture"]["data"]["url"] except Exception as e: self.logger_api.warning(e) if email: q_user = self.DALDatabase(self.DALDatabase.auth_user.email == email).select().first() if q_user: q_user.update_record(activated=True) timeout_token_user = self.projectConfig['BACKEND'][self.app_name]['default_time_user_token_expire_remember_me'] t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], timeout_token_user ) content = { 'id': str(q_user.id), 'email': email } token_user = t_user.dumps(content) token_user = token_user.decode('utf-8') q_role = self.DALDatabase( (self.DALDatabase.auth_membership.auth_user == q_user.id) & (self.DALDatabase.auth_group.id == self.DALDatabase.auth_membership.auth_group) ).select(self.DALDatabase.auth_group.role, orderby=self.DALDatabase.auth_group.grade) roles = [x.role for x in q_role] role = None if roles: role = roles[-1] q_user.update_record(login_attempts=0) t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_client_token_expire'] ) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]["secret_key"], salt="url_secret_key" ) r_client = self.DALDatabase(self.DALDatabase.client.token == self.phanterpwa_client_token).select().first() if r_client: r_client.delete_record() id_client = self.DALDatabase.client.insert(auth_user=q_user.id, date_created=datetime.now()) q_client = self.DALDatabase(self.DALDatabase.client.id == id_client).select().first() content = { 'id_user': str(q_user.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_url = t_url.dumps(content) token_client = t_client.dumps(content) token_client = token_client.decode('utf-8') q_client.update_record( token=token_client, date_created=datetime.now(), remember_me=True, locked=False, ) if not q_user.permit_mult_login: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == q_user.id) & (self.DALDatabase.client.token != token_client) ).select() if r_client: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == q_user.id) & (self.DALDatabase.client.token != token_client) ).delete() user_image = PhanterpwaGalleryUserImage(q_user.id, self.DALDatabase, self.projectConfig) redirect = "{0}#_phanterpwa:/oauth/{1}/{2}".format( origin if origin else self.projectConfig['BACKEND'][self.app_name]['http_address'], social_name, state ) q_state.update_record(user_credentials=json.dumps({ 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, 'auth_user': { 'id': str(q_user.id), 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'activated': True, 'image': user_image.id_image, 'social_image': social_image, 'two_factor': False, 'multiple_login': q_user.permit_mult_login, 'social_login': social_name } })) self.DALDatabase.commit() self.set_status(200) return self.write( str(HTML(HEAD(), BODY(SCRIPT("window.location = '{0}'".format(redirect)))))) else: new_password = os.urandom(3).hex() password_hash = pbkdf2_sha512.hash("password{0}{1}".format( new_password, self.projectConfig['BACKEND'][self.app_name]['secret_key'])) table = self.DALDatabase.auth_user social_image = googleapi_user.get("picture", None) first_name = googleapi_user.get("given_name", "") last_name = googleapi_user.get("family_name", "") dict_arguments = { "first_name": first_name, "last_name": last_name, "email": email, "password_hash": password_hash, "activated": True } result = FieldsDALValidateDictArgs( dict_arguments, *[table[x] for x in table.fields if x in [ "first_name", "last_name", "email", "password_hash"]] ) r = result.validate_and_insert(self.DALDatabase.auth_user) if r and r.id: q_user = self.DALDatabase(self.DALDatabase.auth_user.id == r.id).select().first() id_user = q_user.id q_user.update_record(activated=True) if r.id == 1: role = "root" id_role = self.DALDatabase(self.DALDatabase.auth_group.role == 'root').select().first() if id_role: self.DALDatabase.auth_membership.insert(auth_user=1, auth_group=id_role.id) else: role = "user" self.DALDatabase.auth_membership.insert(auth_user=r.id, auth_group=3) t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_user_token_expire'] ) content_user = { 'id': str(r.id), 'email': dict_arguments['email'] } token_user = t_user.dumps(content_user) token_user = token_user.decode('utf-8') token_client = self.phanterpwa_client_token id_client = self.DALDatabase.client.update_or_insert(auth_user=r.id) t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][self.app_name]['default_time_client_token_expire'] ) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]["secret_key"], salt="url_secret_key" ) content_client = { 'id_user': str(r.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_url = t_url.dumps(content_client) token_client = t_client.dumps(content_client) token_client = token_client.decode('utf-8') q_client = self.DALDatabase(self.DALDatabase.client.id == id_client).select().first() q_client.update_record( token=token_client, date_created=datetime.now() ) r_client = self.DALDatabase(self.DALDatabase.client.token == self.phanterpwa_client_token).select().first() if r_client: r_client.delete_record() if not q_user.permit_mult_login: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token != self.phanterpwa_client_token) ).select() if r_client: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token != self.phanterpwa_client_token) ).remove() user_image = PhanterpwaGalleryUserImage(r.id, self.DALDatabase, self.projectConfig) self.set_status(201) roles = ["user"] role = "user" redirect = "{0}#_phanterpwa:/oauth/{1}/{2}".format( origin if origin else self.projectConfig['BACKEND'][self.app_name]['http_address'], social_name, state ) q_state.update_record(user_credentials=json.dumps({ 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, 'auth_user': { 'id': str(q_user.id), 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'activated': True, 'image': user_image.id_image, 'social_image': social_image, 'two_factor': False, 'multiple_login': q_user.permit_mult_login, 'social_login': social_name } })) self.DALDatabase.commit() return self.write( str(HTML(HEAD(), BODY(SCRIPT("window.location = '{0}'".format(redirect)))))) message = "An error occurred while trying to authenticate." self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'i18n': { 'message': self.T(message) } })
def delete(self, *args): id_session = args[0] t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][ self.app_name]['default_time_client_token_expire']) if self.phanterpwa_client_token: db = self.DALDatabase # self.phanterpwa_current_client.as_dict(datetime_to_str=True) q = db(db.client.token == self.phanterpwa_client_token).select().first() if q: token_content_client = None try: token_content_client = t_client.loads( self.phanterpwa_client_token) except BadSignature: msg = 'The client have a invalid client-token, a new one has been generated.' token_content_client = None except SignatureExpired: msg = 'The client have a expired client-token, a new one has been generated.' token_content_client = None if token_content_client: sessions = [] q_sessions = db(db.client.auth_user == self.phanterpwa_current_user.id).select( orderby=db.client.date_created) for x in q_sessions: this_session = False if x.token == self.phanterpwa_client_token: this_session = True if (str(x.id) == id_session) and not this_session: x.delete_record() else: tc = None try: tc = t_client.loads(x.token) except: tc = None user_agent = None remote_addr = None date_created = x.date_created if tc: remote_addr = tc['remote_addr'] user_agent = tc['user_agent'] sessions.append( dict(user_agent=user_agent, agent=user_agent_parse(user_agent), remote_addr=remote_addr, date_created=str(date_created), this_session=this_session, identify=x.id)) self.set_status(200) self.write({ 'status': 'OK', 'code': 200, 'message': 'Deleted Session', 'i18n': { 'message': self.T('Deleted Session') }, 'sessions': sessions })
def get(self, *args, **kargs): q_client = self.DALDatabase(self.DALDatabase.client.token == self. phanterpwa_client_token).select().first() remember_me = q_client.remember_me timeout_to_resign = self.projectConfig['BACKEND'][ self.app_name]["timeout_to_resign"] time_resing_client = int(self.projectConfig['BACKEND'][ self.app_name]['default_time_client_token_expire'] * 0.8) + 1 if remember_me: timeout_to_resign = int( self.projectConfig['BACKEND'][self.app_name] ['default_time_user_token_expire_remember_me'] * 0.8) + 1 t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][ self.app_name]['default_time_client_token_expire']) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]['secret_key'], salt="url_secret_key") if q_client.last_resign is None or ( (q_client.last_resign + timedelta(seconds=timeout_to_resign)) < datetime.now()): timeout_token_user = self.projectConfig['BACKEND'][ self.app_name]['default_time_user_token_expire'] if remember_me: timeout_token_user = self.projectConfig['BACKEND'][ self. app_name]['default_time_user_token_expire_remember_me'] t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], timeout_token_user) content_client = { 'id_user': str(self.phanterpwa_current_user.id), "id_client": str(q_client.id), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip, } content_user = { 'id': str(self.phanterpwa_current_user.id), 'email': self.phanterpwa_current_user.email } token_user = t_user.dumps(content_user) token_user = token_user.decode('utf-8') token_client = self.phanterpwa_client_token token_url = t_url.dumps(content_client) msg = 'Re-sign just user token' q_client.update_record(last_resign=datetime.now()) if not self.phanterpwa_current_user.permit_mult_login: self.DALDatabase((self.DALDatabase.client.auth_user == self.phanterpwa_current_user.id) & (self.DALDatabase.client.token != self.phanterpwa_client_token)).delete() self.DALDatabase.commit() self.set_status(200) return self.write({ "status": "OK", 'message': msg, 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, "i18n": { "message": self.T(msg) } }) elif q_client.date_created +\ timedelta(seconds=time_resing_client) < datetime.now(): q_client.delete_record() timeout_token_user = self.projectConfig['BACKEND'][ self.app_name]['default_time_user_token_expire'] if remember_me: timeout_token_user = self.projectConfig['BACKEND'][ self. app_name]['default_time_user_token_expire_remember_me'] t_user = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], timeout_token_user) new_client = self.DALDatabase.client.insert( auth_user=q_client.auth_user, remember_me=q_client.remember_me, last_resign=datetime.now(), date_created=datetime.now()) content = { 'id_user': str(self.phanterpwa_current_user.id), "id_client": str(new_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip, } content_user = { 'id': str(self.phanterpwa_current_user.id), 'email': self.phanterpwa_current_user.email } token_user = t_user.dumps(content_user) token_user = token_user.decode('utf-8') token_url = t_url.dumps(content) token_client = t_client.dumps(content) token_client = token_client.decode("utf-8") q_client.delete_record() q_client = self.DALDatabase( self.DALDatabase.client.id == new_client).select().first() q_client.update_record(token=token_client) self.phanterpwa_client_token = token_client msg = 'Re-sign client token, user token and url token' if not self.phanterpwa_current_user.permit_mult_login: self.DALDatabase((self.DALDatabase.client.auth_user == self.phanterpwa_current_user.id) & (self.DALDatabase.client.token != self.phanterpwa_client_token)).delete() self.DALDatabase.commit() self.set_status(200) return self.write({ "status": "OK", 'message': msg, 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, "i18n": { "message": self.T(msg) } }) else: msg = "This is not the time to re-sign" self.set_status(202) return self.write({ 'status': 'Accepted', 'message': msg, "i18n": { "message": self.T(msg) } })
def post(self, *args, **kargs): """ Receive captcha user choice and response with csrf token """ form_identify = args[0] list_forms = self.list_forms dict_arguments = { k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments } choice = dict_arguments['user_choice'] sign = dict_arguments['signature'] id_client = int(self.phanterpwa_client_token_checked["id_client"]) q_captcha = self.DALDatabase( self.DALDatabase.captcha.token == sign).select().first() if q_captcha: self.DALDatabase((self.DALDatabase.captcha.client == id_client) & (self.DALDatabase.captcha.form_identify == form_identify)).delete() self.DALDatabase((self.DALDatabase.csrf.client == id_client) & (self.DALDatabase.csrf.form_identify == form_identify)).delete() q_captcha.delete_record() captcha = Captcha(form_identify, "csrf-{0}".format(self.projectConfig['BACKEND'][ self.app_name]['secret_key']), self.projectConfig['BACKEND'][self.app_name] ['default_time_csrf_token_expire'], translator=self.Translator_captcha) if captcha.check(sign, choice): id_csrf = self.DALDatabase.csrf.insert( form_identify=form_identify, user_agent=self.phanterpwa_user_agent, ip=self.phanterpwa_remote_ip, client=id_client) if id_csrf: t = Serialize( "csrf-{0}".format(self.projectConfig['BACKEND'][ self.app_name]['secret_key']), self.projectConfig['BACKEND'][ self.app_name]['default_time_csrf_token_expire']) sign_captha = t.dumps({ 'id': str(id_csrf), 'form_identify': form_identify, 'user_agent': self.phanterpwa_user_agent, 'ip': self.phanterpwa_remote_ip }) sign_captha = sign_captha.decode("utf-8") q_csrf = self.DALDatabase( self.DALDatabase.csrf.id == id_csrf).select().first() q_csrf.update_record(token=sign_captha) self.DALDatabase.commit() self.set_status(200) return self.write({ "status": "OK", "code": 200, "message": "Captcha resolved", "i18n": { "message": self.T("Captcha resolved") }, "captcha": captcha.html_ok.xml(), "csrf": sign_captha }) else: id_client = int( self.phanterpwa_client_token_checked["id_client"]) if form_identify in list_forms: self.DALDatabase( (self.DALDatabase.captcha.client == id_client) & (self.DALDatabase.captcha.form_identify == form_identify)).delete() captcha = Captcha( form_identify, secret_key="csrf-{0}".format( self.projectConfig['BACKEND'][ self.app_name]['secret_key']), time_token_expire=self.projectConfig['BACKEND'][ self.app_name]['default_time_csrf_token_expire'], translator=self.Translator_captcha) html_captcha = captcha.html.xml() signature = captcha.signature self.DALDatabase.captcha.insert( token=signature, form_identify=form_identify, user_agent=self.phanterpwa_user_agent, ip=self.phanterpwa_remote_ip, date_created=datetime.now(), client=id_client) self.DALDatabase.commit() self.set_status(400) return self.write({ "status": "Bad Request", "code": 400, "captcha": html_captcha, "signature": signature, "message": "Incorrect captcha", "i18n": { "message": self.T("Incorrect captcha") } }) else: self.DALDatabase.commit() self.set_status(400) return self.write({ "status": "Bad Request", "code": 400, "message": "Incorrect captcha", "i18n": { "message": self.T("Incorrect captcha") } }) else: self.DALDatabase.commit() self.set_status(400) return self.write({ "status": "Bad Request", "code": 400, "message": "Incorrect captcha, not found.", "i18n": { "message": self.T("Incorrect captcha, not found.") } })
def get(self, *args, **kargs): self.phanterpwa_client_token = self.request.headers.get( 'phanterpwa-client-token') self.phanterpwa_authorization = self.request.headers.get( 'phanterpwa-authorization') t_client = Serialize( self.projectConfig['BACKEND'][self.app_name]['secret_key'], self.projectConfig['BACKEND'][ self.app_name]['default_time_client_token_expire']) t_url = URLSafeSerializer( self.projectConfig['BACKEND'][self.app_name]['secret_key'], salt="url_secret_key") msg = 'The client does not have a client-token, a new one has been generated.' q = None if self.phanterpwa_client_token: q = self.DALDatabase(self.DALDatabase.client.token == self. phanterpwa_client_token).select().first() if q: token_content_client = None try: token_content_client = t_client.loads( self.phanterpwa_client_token) except BadSignature: msg = 'The client have a invalid client-token, a new one has been generated.' token_content_client = None except SignatureExpired: msg = 'The client have a expired client-token, a new one has been generated.' token_content_client = None if token_content_client: if token_content_client[ 'user_agent'] == self.phanterpwa_user_agent: if 'id_user' in token_content_client: token_url = t_url.dumps({**token_content_client}) if self.phanterpwa_authorization: t_user = Serialize( self.projectConfig['BACKEND'][ self.app_name]['secret_key'], self.projectConfig['BACKEND'][ self.app_name] ['default_time_user_token_expire']) token_content_user = None try: token_content_user = t_user.loads( self.phanterpwa_authorization) except BadSignature: token_content_user = None except SignatureExpired: token_content_user = None if token_content_user and 'id' in token_content_user: id_user = token_content_user['id'] q_user = self.DALDatabase( self.DALDatabase.auth_user.id == id_user).select().first() q_client = self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token == self.phanterpwa_client_token) ).select().first() if q_user and q_client: msg = "".join([ 'The client-token is valid and belongs ', 'to a login user, will be reused.' ]) time_resing_client = int( self.projectConfig['BACKEND'][ self.app_name] ['default_time_client_token_expire'] * 0.8) + 1 if q_client.date_created +\ timedelta(seconds=time_resing_client) < datetime.now(): new_client = self.DALDatabase.client.insert( auth_user=q_client.auth_user, remember_me=q_client. remember_me, last_resign=datetime.now(), date_created=datetime.now()) content = { 'id_user': str(q_user.id), "id_client": str(new_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip, } token_url = t_url.dumps(content) token_client = t_client.dumps( content) token_client = token_client.decode( "utf-8") q_client.delete_record() q_client = self.DALDatabase( self.DALDatabase.client.id == new_client).select().first() q_client.update_record( token=token_client) self.phanterpwa_client_token = token_client msg = "".join([ 'The client-token is valid and belongs ', 'to a login user, but a new one has been generated.' ]) if not q_user.permit_mult_login: self.DALDatabase( (self.DALDatabase.client. auth_user == id_user) & (self.DALDatabase.client. token != self. phanterpwa_client_token) ).delete() q_role = self.DALDatabase( (self.DALDatabase.auth_membership. auth_user == q_user.id) & (self.DALDatabase.auth_group.id == self.DALDatabase. auth_membership.auth_group) ).select( self.DALDatabase.auth_group.id, self.DALDatabase.auth_group.role, orderby=self.DALDatabase. auth_group.grade) roles = [x.role for x in q_role] dict_roles = { x.id: x.role for x in q_role } role = None if roles: role = roles[-1] self.DALDatabase.commit() user_image = PhanterpwaGalleryUserImage( q_user.id, self.DALDatabase, self.projectConfig) self.set_status(200) return self.write( { 'status': 'OK', 'code': 200, 'message': msg, 'auth_user': { 'id': q_user.id, 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': q_user.email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'dict_roles': dict_roles, 'activated': q_user.activated, 'image': user_image.id_image, 'two_factor': q_user.two_factor_login, 'multiple_login': q_user.permit_mult_login, 'locale': q_user.locale, 'social_login': None }, 'i18n': { 'message': self.T(msg), 'auth_user': { 'role': self.T(role) } }, 'client_token': self.phanterpwa_client_token, 'url_token': token_url, }) else: msg = "".join([ 'The client-token is valid and belongs ', 'to a logout user, will be reused.' ]) self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'message': msg, 'auth_user': '******', 'i18n': { 'message': self.T(msg), 'auth_user': self.T('logout') }, 'client_token': self.phanterpwa_client_token, 'url_token': token_url, }) else: msg = 'The client-token is valid and anonymous, will be reused' self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'message': msg, 'auth_user': '******', 'i18n': { 'message': self.T(msg), 'auth_user': self.T('anonymous') }, 'client_token': self.phanterpwa_client_token }) else: msg = "".join([ 'The client-token is valid but appears to ', 'belong to another client, a new one has been generated.' ]) else: if self.phanterpwa_authorization: t_user = Serialize( self.projectConfig['BACKEND'][self.app_name] ['secret_key'], self.projectConfig['BACKEND'] [self.app_name]['default_time_user_token_expire']) token_content_user = None try: token_content_user = t_user.loads( self.phanterpwa_authorization) except BadSignature: token_content_user = None except SignatureExpired: token_content_user = None if token_content_user and 'id' in token_content_user: id_user = token_content_user['id'] if int(token_content_user['id']) == int(id_user): q_user = self.DALDatabase( self.DALDatabase.auth_user.id == id_user).select().first() if q_user: content = { 'id_user': str(q_user.id), "id_client": str(q.id), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip, } token_url = t_url.dumps(content) token_client = t_client.dumps(content) token_client = token_client.decode('utf-8') q.update_record( token=token_client, id_user=q_user.id, date_created=datetime.now()) if not q_user.permit_mult_login: self.DALDatabase( (self.DALDatabase.client.auth_user == id_user) & (self.DALDatabase.client.token != self.phanterpwa_client_token) ).delete() q_role = self.DALDatabase( (self.DALDatabase.auth_membership. auth_user == q_user.id) & (self.DALDatabase.auth_group.id == self.DALDatabase.auth_membership. auth_group)).select( self.DALDatabase.auth_group.id, self.DALDatabase.auth_group.role, orderby=self.DALDatabase. auth_group.grade) roles = [x.role for x in q_role] dict_roles = {x.id: x.role for x in q_role} role = None if roles: role = roles[-1] self.DALDatabase.commit() msg = "".join([ 'The client token is valid but expired, ', 'a new one has been generated.' ]) user_image = PhanterpwaGalleryUserImage( q_user.id, self.DALDatabase, self.projectConfig) self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'message': msg, 'auth_user': { 'id': q_user.id, 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': q_user.email, 'remember_me': q.remember_me, 'roles': roles, 'role': role, 'dict_roles': dict_roles, 'activated': q_user.activated, 'image': user_image.id_image, 'two_factor': q_user.two_factor_login, 'multiple_login': q_user.permit_mult_login, 'locale': q_user.locale, 'social_login': None }, 'i18n': { 'message': self.T(msg), 'auth_user': { 'role': self.T(role) } }, 'client_token': token_client, 'url_token': token_url }) else: msg = 'The client have a invalid client-token, a new one has been generated.' q.delete_record() else: msg = 'The client have a invalid client-token, not found, a new one has been generated.' if q: id_client = q.id else: id_client = self.DALDatabase.client.insert( date_created=datetime.now()) content = { "id_client": id_client, 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_client = t_client.dumps(content) token_client = token_client.decode('utf-8') q_client = self.DALDatabase( self.DALDatabase.client.id == id_client).select( self.DALDatabase.client.id).first() if q_client: q_client.update_record(token=token_client) self.DALDatabase.commit() self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'message': msg, 'auth_user': '******', 'i18n': { 'message': self.T(msg), 'auth_user': self.T('anonymous') }, 'client_token': token_client })
def post(self, *args): self.phanterpwa_authorization = self.request.headers.get( 'phanterpwa-authorization') dict_arguments = { k: self.request.arguments.get(k)[0].decode('utf-8') for k in self.request.arguments } if dict_arguments.get('edata'): used_temporary = None edata = dict_arguments['edata'] email, password = edata.split(":") email = base64.b64decode(email).decode('utf-8').strip().lower() password = base64.b64decode(password).decode('utf-8') q_user = self.DALDatabase( self.DALDatabase.auth_user.email == email).select().first() if q_user: if not q_user.login_attempts: q_user.update_record(login_attempts=1) else: q_user.update_record(login_attempts=q_user.login_attempts + 1) result = None try: result = pbkdf2_sha512.verify( "password{0}{1}".format( password, self.projectConfig['BACKEND'][ self.app_name]['secret_key']), q_user.password_hash) except Exception: self.logger_api.error("Problem on check password", exc_info=True) finally: if not result and\ q_user.temporary_password_expire and\ (datetime.now() < q_user.temporary_password_expire) and q_user.temporary_password_hash: result = pbkdf2_sha512.verify( "password{0}{1}".format( password, self.projectConfig['BACKEND'][ self.app_name]['secret_key']), q_user.temporary_password_hash) if result: used_temporary = password q_user.update_record(login_attempts=0) if q_user.login_attempts > self.projectConfig['BACKEND'][ self.app_name]['max_login_attempts']: if q_user.datetime_next_attempt_to_login and\ (datetime.now() <= q_user.datetime_next_attempt_to_login): t_delta = q_user.datetime_next_attempt_to_login - datetime.now( ) msg = "Please, wait approximately {time_next_attempt} to try again." tna = int(t_delta.total_seconds()) message = msg.format( time_next_attempt=humanize_seconds(tna)) message_i18n = self.T(msg).format( time_next_attempt=humanize_seconds( tna, self.i18nTranslator)) self.DALDatabase.commit() self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'login_attempts': q_user.login_attempts, 'i18n': { 'message': message_i18n, } }) else: q_user.update_record(login_attempts=1) if result: remember_me = False timeout_token_user = self.projectConfig['BACKEND'][ self.app_name]['default_time_user_token_expire'] rem_me = checkbox_bool(dict_arguments['remember_me']) if rem_me: remember_me = True timeout_token_user = self.projectConfig['BACKEND'][ self.app_name][ 'default_time_user_token_expire_remember_me'] t_user = Serialize( self.projectConfig['BACKEND'][self.app_name] ['secret_key'], timeout_token_user) content = {'id': str(q_user.id), 'email': email} token_user = t_user.dumps(content) token_user = token_user.decode('utf-8') q_role = self.DALDatabase(( self.DALDatabase.auth_membership.auth_user == q_user.id ) & (self.DALDatabase.auth_group.id == self.DALDatabase.auth_membership.auth_group)).select( self.DALDatabase.auth_group.id, self.DALDatabase.auth_group.role, orderby=self.DALDatabase.auth_group.grade) roles = [x.role for x in q_role] dict_roles = {x.id: x.role for x in q_role} roles_id = [x.id for x in q_role] role = None if roles: role = roles[-1] q_user.update_record(login_attempts=0) t_client = Serialize( self.projectConfig['BACKEND'][self.app_name] ['secret_key'], self.projectConfig['BACKEND'][ self.app_name]['default_time_client_token_expire']) t_url = URLSafeSerializer(self.projectConfig['BACKEND'][ self.app_name]["secret_key"], salt="url_secret_key") r_client = self.DALDatabase( self.DALDatabase.client.token == self.phanterpwa_client_token).select().first() if r_client: r_client.delete_record() id_client = self.DALDatabase.client.insert( auth_user=q_user.id, date_created=datetime.now()) q_client = self.DALDatabase(self.DALDatabase.client.id == id_client).select().first() content = { 'id_user': str(q_user.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } token_url = t_url.dumps(content) token_client = t_client.dumps(content) token_client = token_client.decode('utf-8') q_client.update_record( token=token_client, date_created=datetime.now(), remember_me=remember_me, locked=False, ) if not q_user.permit_mult_login: r_client = self.DALDatabase( (self.DALDatabase.client.auth_user == q_user.id) & (self.DALDatabase.client.token != token_client) ).select() if r_client: r_client = self.DALDatabase(( self.DALDatabase.client.auth_user == q_user.id ) & (self.DALDatabase.client.token != token_client) ).delete() self.DALDatabase.commit() user_image = PhanterpwaGalleryUserImage( q_user.id, self.DALDatabase, self.projectConfig) if ( q_user.two_factor_login or two_factor ) and not used_temporary and not self.phanterpwa_form_identify == "user_locked": two_factor_serialize = URLSafeSerializer( self.projectConfig['BACKEND'][ self.app_name]["secret_key"], salt="two_factor_url") content = { 'id_user': str(q_user.id), 'id_client': str(id_client), 'user_agent': self.phanterpwa_user_agent, 'remote_addr': self.phanterpwa_remote_ip } two_factor_url = two_factor_serialize.dumps(content) two_factor_code = generate_activation_code() self.Translator_email.direct_translation = self.phanterpwa_language keys_formatter = dict( app_name=self.projectConfig['PROJECT']['name'], user_name="{0} {1}".format(q_user.first_name, q_user.last_name), code=two_factor_code, time_expires=humanize_seconds( self.projectConfig['BACKEND'][self.app_name] ['default_time_two_factor_code_expire'], self.Translator_email), user_agent=self.phanterpwa_user_agent, user_ip=self.phanterpwa_remote_ip, copyright=interpolate( self.projectConfig['CONTENT_EMAILS'] ['copyright'], {'now': datetime.now().year}), link_to_your_page=self.projectConfig[ 'CONTENT_EMAILS']['link_to_your_site']) email_password.text.formatter(keys_formatter) text_email = email_two_factor_code.text.html( minify=True, translate=True, formatter=keys_formatter, i18nInstance=self.Translator_email, dictionary=self.phanterpwa_language, do_not_translate=["\n", " ", "\n\n", " "], escape_string=False) html_email = email_two_factor_code.html.html( minify=True, translate=True, formatter=keys_formatter, i18nInstance=self.Translator_email, dictionary=self.phanterpwa_language, do_not_translate=["\n", " ", "\n\n", " "], escape_string=False) e_mail = MailSender( self.projectConfig['EMAIL']['default_sender'], self.projectConfig['EMAIL']['password'], q_user.email, subject="Two factor authentication code", text_message=text_email, html_message=html_email, server=self.projectConfig['EMAIL']['server'], port=self.projectConfig['EMAIL']['port'], use_tls=self.projectConfig['EMAIL']['use_tls'], use_ssl=self.projectConfig['EMAIL']['use_ssl']) result = "" try: if self.projectConfig["PROJECT"]["debug"]: self.logger_api.warning( "TWO FACTOR CODE: {0}".format( two_factor_code)) else: self.logger_api.warning( "Email from '{0}' to '{1}' -> Activation Code: {2}" .format( self.projectConfig['EMAIL'] ['default_sender'], q_user.email, two_factor_code)) e_mail.send() except Exception as e: result = "Email from '{0}' to '{1}' don't send! -> Error: {2} -> password: {3}".format( self.projectConfig['EMAIL']['default_sender'], dict_arguments['email'], e, two_factor_code) self.logger_api.error(result, exc_info=True) message = "There was an error trying to send the email." message_i18n = self.T( "There was an error trying to send the email.") self.DALDatabase.rollback() self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'i18n': { 'message': message_i18n } }) else: self.DALDatabase.two_factor_login.insert( auth_user=q_user.id, two_factor_url=two_factor_url, two_factor_code=two_factor_code) message = 'A code has been sent to your email.' message_i18n = self.T( 'A code has been sent to your email.') self.DALDatabase.commit() self.set_status(206) return self.write({ 'status': 'OK', 'message': message, 'client_token': token_client, 'as': self.phanterpwa_form_identify, 'auth_user': { 'remember_me': q_client.remember_me }, 'i18n': { 'message': message_i18n }, 'authorization_url': two_factor_url }) else: self.set_status(200) return self.write({ 'status': 'OK', 'code': 200, 'message': 'The user is logged', 'authorization': token_user, 'client_token': token_client, 'url_token': token_url, 'used_temporary': used_temporary, 'auth_user': { 'id': str(q_user.id), 'first_name': E(q_user.first_name), 'last_name': E(q_user.last_name), 'email': email, 'remember_me': q_client.remember_me, 'roles': roles, 'role': role, 'dict_roles': dict_roles, 'roles_id': roles_id, 'activated': q_user.activated, 'image': user_image.id_image, 'two_factor': q_user.two_factor_login, 'multiple_login': q_user.permit_mult_login, 'locale': q_user.locale, 'social_login': None }, 'i18n': { 'message': self.T('The user is logged'), 'auth_user': { 'role': self.T(role) } } }) else: q_user.update_record( temporary_password_expire=datetime.now() + timedelta(seconds=self.projectConfig['BACKEND'][ self.app_name] ['default_time_temporary_password_expire']), datetime_next_attempt_to_login=datetime.now() + timedelta(seconds=self.projectConfig['BACKEND'][ self.app_name]['timeout_to_next_login_attempt'])) msg = 'Wrong password! Attempt {attempt_number} from {max_attempts}' message = msg.format( attempt_number=q_user.login_attempts, max_attempts=self.projectConfig['BACKEND'][ self.app_name]['max_login_attempts']) message_i18n = self.T(msg).format( attempt_number=q_user.login_attempts, max_attempts=self.projectConfig['BACKEND'][ self.app_name]['max_login_attempts']) self.DALDatabase.commit() self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': message, 'login_attempts': q_user.login_attempts, 'i18n': { 'message': message_i18n } }) else: self.set_status(401) return self.write({ 'status': 'Unauthorized', 'code': 401, 'message': 'Invalid password or email', 'i18n': { 'message': self.T('Invalid password or email') } }) self.set_status(400) return self.write({ 'status': 'Bad Request', 'code': 400, 'message': 'Invalid password or email', 'as': dict_arguments.get('edata'), 'i18n': { 'message': self.T('Invalid password or email') } })
def get_reset_token(self, expires_sec=1800): s = Serialize(current_app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8')