def post(self, *args, **kwargs): notif_token = self.get_argument('notification_token', None) if not notif_token: raise InvalidInput('notification_token cannot be empty') user_model = UserModel() user_model.update_notification_token_for_user(notif_token, self.get_current_session()) view = JsonView().render() self.finish(view)
def delete(self, uid): """ 删除用户 :return: """ users = UserModel.find_by_id(uid) if not users: return dict(code=404, msg='not found', data=None) else: UserModel.delete(uid) return dict(code=200, msg='success', data=None)
def add_user(): error = None form = CreateUserForm() if form.validate_on_submit(): try: UserModel.save(username=request.form['username'], password=request.form['password']) except Exception, e: error = u"そのユーザ名は登録できません" else: flash(u"登録が完了しました") return redirect(url_for('index'))
def add_user(): error = None form = CreateUserForm() if form.validate_on_submit(): try: UserModel.save(username=request.form['username'], password=request.form['password']) except Exception, e: error = u"そのユーザ名は登録できません" else: flash(u"登録が完了しました") return redirect(url_for('index'))
def post(self): super(UserApi, self).post() code = 0 value_list = self.get_form_data() userinfo = dict(zip(self.cloumn, value_list)) userinfo['password'] = request.form.get('password') user = UserModel(**userinfo) user.save() if not user.success: return self.render_json(code=1003) self.log(info=userinfo['name']) return self.render_json()
def post(self, *args, **kwargs): email = self.get_argument('user_email', None) if not email: raise InvalidInput('user_email cannot be empty') user_model = UserModel() user_id = user_model.get_user_id_from_email(email) if not user_id: user_id = user_model.create_user_in_db(email) session = user_model.create_session(user_id) view = JsonView({'session': session}).render() self.finish(view)
def post(self, *args, **kwargs): self.set_header("Access-Control-Allow-Origin", "http://getpixelbots.com") self.set_header("Access-Control-Allow-Credentials", 'true') email = self.get_argument('email', None) if not email: raise InvalidInput('email cannot be empty') if not re.match(r'[^@]+@[^@]+\.[^@]+', email): raise InvalidInput('email is not valid') user_model = UserModel(); user_model.insert_subscription_invite(email) view = JsonView() self.finish(view.render())
def authenticate_credentials(self, token): try: payload = jwt.decode(token, "SECRET_KEY") SessionModel.objects(jwt_token=token) email = payload['email'] user_id = payload['user_id'] sessions = SessionModel.objects(jwt_token=token, user_id=user_id, email=email) if len(sessions) == 0: raise exceptions.AuthenticationFailed({ 'Error': "Token mismatch", 'status': "401" }) else: user = UserModel.objects(user_id=sessions[0]["user_id"], email=sessions[0]["email"]) user_data = json.loads(user[0].to_json()) return (user_data, token) except jwt.exceptions.InvalidTokenError: raise exceptions.AuthenticationFailed() except: print "Unexpected error:", sys.exc_info() traceback.print_tb(sys.exc_info()[2]) raise exceptions.AuthenticationFailed(str(sys.exc_info()))
def home(): if request.method == 'POST': username = request.form.get('username') user = UserModel.query.filter_by(username=username).first() if not user: user = UserModel(username=username) db.session.add(user) db.session.commit() session['id'] = user.id next_page = request.args.get('next') if next_page: return redirect(next_page) return redirect('/') user = current_user() if user: clients = OAuth2ClientModel.query.filter_by(user_id=user.id).all() else: clients = [] return render_template('home.html', user=user, clients=clients)
def getUserByName(username): """ 根据username获取用户 """ assert isinstance(username, str) result = db.user.find_one({'username': username}) return UserModel(result=result)
def put(self, uid): """更新用户资料""" assert current_user.id == uid # 断言判断当前用户是本人,十分懒人的处理了,哈哈 form = UserForm() user = UserModel.find_by_id(uid) user.update(**form.form) return dict(code=200, msg='success', data=user.asdict())
def login(self): user_model = UserModel() key = SECRET_KEY password = self.password+key self.password = md5(password.encode('utf8')).hexdigest() model_result = user_model.login(self.username,self.password) if model_result: data = { 'id': model_result[0], 'nickname':model_result[1] } return data else: return None
def post(self): name = request.json['name'] birth_date = request.json['birthDate'] gender = request.json['gender'] phone_number = request.json['phoneNumber'] disturbance_factor = request.json['disturbanceFactor'] favorite_food = request.json['favoriteFood'] user = UserModel(name=name, birth_date=birth_date, gender=gender, phone_number=phone_number) user.save() SurveyModel(disturbance_factor=disturbance_factor, favorite_food=favorite_food, user=user).save() return Response('', 200)
def register(): form = RegisterForm(meta=dict(csrf=False)) if form.validate(): user, msg = UserModel.register_user(form.form) if user: return dict(code=200, msg=msg, data=user.asdict()) else: return dict(code=201, msg=msg, data=None) else: return form.errors
def post(self, *args, **kwargs): #todo: handle openid login passwordless email = self.get_argument('user_email', None) if not email: raise InvalidInput('user_email cannot be empty') password = self.get_argument('user_password', None) if not email: raise InvalidInput('user_password cannot be empty') is_sign_up = self.get_argument('is_sign_up', None) user_model = UserModel() user_id = user_model.get_user_id_from_email(email) if not user_id: if is_sign_up: #exception here is internal error... pretty serious user_id = user_model.create_user_in_db(email, password) else: #raise auth error raise InvalidInput('wrong username or password') else: user_id = user_model.get_user_id_from_login(email, password) if not user_id: #raise auth error raise InvalidInput('wrong username or password') session = user_model.create_session(user_id) view = JsonView({'session': session}).render() self.finish(view)
def login(): form = LoginForm(meta=dict(csrf=False)) if form.validate(): user = UserModel.validate_login(request.form) if user: login_user(user) return dict(code=200, msg='success', data=user.asdict()) else: return dict(code=401, msg='incorrect username or password', data=None) else: return form.errors
def login(request): if request.data.get("google_id_token") is not None: auth_method = "google" google_id_token = request.data["google_id_token"] elif request.data.get("email") is not None and request.data.get("password") is not None: auth_method = "email" email = request.data.get("email") password = request.data.get("password") else: return Response(status=status.HTTP_400_BAD_REQUEST) try: full_name = "" profile_image_url = None if auth_method == "google": try: id_info = id_token.verify_oauth2_token( google_id_token, googlerequests.Request(), "3890518873-9igg3o5c5c45a3cnq3fku68jrvc5ricj.apps.googleusercontent.com") except ValueError as value_error: print(value_error) return Response(data=str(value_error), status=status.HTTP_401_UNAUTHORIZED) print(id_info) if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: return Response(status=status.HTTP_403_FORBIDDEN, data='Wrong issuer {}'.format(id_info['iss'])) if id_info.get('hd') != "deepen.ai" and id_info.get('hd') != "deepenai.com" \ and id_info["email"] != "*****@*****.**" \ and id_info["email"] != "*****@*****.**": return Response(status=status.HTTP_403_FORBIDDEN, data='Unauthorized user {}'.format(id_info)) user_id = id_info["sub"] email = id_info["email"] full_name = id_info["name"] profile_image_url = id_info["picture"] else: user = UserModel.objects(email=email, password=password) if len(user) == 0: return Response(status=status.HTTP_403_FORBIDDEN, data='Unauthorized user {}'.format(email)) user_id = user[0]["user_id"] email = user[0]["email"] return create_jwt_token(user_id, email, full_name=full_name, profile_image_url=profile_image_url) except: print "Unexpected error:", sys.exc_info() traceback.print_tb(sys.exc_info()[2]) return Response(data=str(sys.exc_info()), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def post(self): email = request.form.get('email') code = request.form.get('code') user = UserModel.query.filter_by(email=email).first() if not code: return self.render_json(code=1001) redis_conn = MyRedis() redis_code = redis_conn.get_str(email) if redis_code: redis_code = redis_code.decode() redis_conn.close_conn() if code == redis_code and redis_code: if not user: UserModel(email=email).save() user = UserModel.query.filter_by(email=email).first() login_user(user, remember=True) return self.render_json(data={'url': '/order'}) return self.render_json(code=1001)
def create_jwt_token(user_id, email, profile_image_url=None, full_name=None): current_time = datetime.now() UserModel.objects(user_id=user_id, email=email).update_one(upsert=True, last_logged_in_date_time=current_time) if email.endswith("deepenai.com"): UserModel.objects(user_id=user_id, email=email).update_one(set__user_role__role="labeller") elif email.endswith("deepen.ai"): UserModel.objects(user_id=user_id, email=email).update_one(set__user_role__role="superadmin") if profile_image_url is not None: UserModel.objects(user_id=user_id, email=email).update_one(set__profile_image_url=profile_image_url) if full_name is not None: UserModel.objects(user_id=user_id, email=email).update_one(set__full_name=full_name) user = UserModel.objects(user_id=user_id, email=email) if len(user) == 0: return Response(status=status.HTTP_401_UNAUTHORIZED, data='Unauthorized user {}'.format(email)) user_data = json.loads(user[0].to_json()) role = user_data.get("user_role", {}).get("role", "") full_name = user_data.get("full_name", "") profile_image_url = user_data.get("profile_image_url") authorized_client_ids = user_data.get("user_role", {}).get("authorized_client_ids", []) payload = { 'user_id': user_id, 'email': email, 'role': role, 'authorized_client_ids': authorized_client_ids, 'expires_at_date_time': (current_time + timedelta(days=1)).isoformat() } jwt_token = jwt.encode(payload, "SECRET_KEY") SessionModel( jwt_token=jwt_token, user_id=user_id, email=email, ).save() data = { "jwt_token": jwt_token, "role": role, "authorized_client_ids": authorized_client_ids, "full_name": full_name } if profile_image_url is not None: data["profile_image_url"] = profile_image_url return Response(data=data)
def get_current_user(self): user_session = self.request.headers.get('X-Pbsession') user_model = UserModel() user_id = user_model.get_user_id_from_session(user_session) return user_id
def get_survey_by_phone_num(cls, phone_number: str): survey = SurveyModel.objects(user=UserModel.objects(phone_number=phone_number).first()).first() if not survey: abort(403) return survey
def save(self, data: Dict, session=None) -> UserModel: try: user = UserModel() user.email = data['email'] user.role_id = data['role_id'] user.name = data['name'] user.password = UserModel.get_hashed_password(data['password']) user.cellphone = data.get('cellphone', '') user.lastname = data['lastname'] user.status = 'active' user.active = True session.add(user) session.commit() print(user) return user except sqlalchemy.exc.IntegrityError as ie: logger.error(str(ie)) session.rollback() raise Exception("El email ya existe") except Exception as exc: logger.error(str(exc)) session.rollback() raise exc
def get_current_user(self): user_session = self.request.headers.get('X-Icsession') user_model = UserModel() user_id = user_model.get_user_id_from_session(user_session) return user_id