def post(self): if not request.json or 'name' not in request.json : abort(400) user = User.objects(email= request.json['email']) if len(user) > 0 : return jsonify( ok=False, errors=['Email already in use. Account creation failed'] ), 403 new_user = User(name= request.json['name'], email= request.json['email'], alive=True ) new_user.description = request.json.get('description', None ) new_user.location = request.json.get('location', None ) new_user.phone = request.json.get('phone', None ) new_user.public = True new_user.save() if 'password' in request.json : auth = Auth( user= new_user, password=request.json['password'], alive=False ) auth.password = auth.hash_password( request.json['email'], request.json['password']) auth.save() return jsonify(ok=True, objects=[new_user.to_json()]), 201
def post(): user_data = json.loads(request.form['params']) image = '' current_app.logger.debug(request.files) for key in request.files: image = request.files[key] current_app.logger.debug(image) response = item_image_bucket.put_object( Body=io.BufferedReader(image).read(), Key=f's3/user-images/' + str(image.filename) ) image = current_app.config['ITEM_IMAGE_BASE'] + response.key user = User( display_name=user_data['display_name'], image=image, name=user_data['name'], name_ruby=user_data['name_ruby'], birthday=user_data['birthday'] ) postUser = user.postRecord() auth = Auth( user_id=postUser.id, email=user_data['email'], password=user_data['password'] ) auth.postRecord() return jsonify({'state': True})
def add_tokens(): phone_number = request.values.get('From')[-10:] user = User.objects(phone_number=str(phone_number)).first() api = request.values.get('API') secret = request.values.get('Secret') access = request.values.get('Access') auth = Auth(api=api, secret=secret, access=access) auth.save() user.auths.append(auth) user.save() return jsonify(success=True)
def postUser(): for num in range(5): user = User(display_name='guest' + str(num), image='', name='山田太郎', name_ruby='ヤマダタロウ', birthday='2001-03-12') postUser = user.postRecord() auth = Auth(user_id=postUser.id, email='guest' + str(num) + '@test.com', password='******') auth.postRecord() return jsonify({'state': True})
def post (self): """ Create a Sheet with given JSON """ user = Auth.getUser() new_sheet = Sheet( name = request.json['name'], description = request.json['description'], #location = request.json.get('location',None), public = request.json.get('public', True), links = request.json.get('links', []), color = request.json.get('color', None), tags = request.json.get('tags', None) ) new_sheet.created_by = user new_sheet.alive = True new_sheet.save() # connect the user to the new sheet user_sheet = UserSheet(name=new_sheet.name, user=user, sheet=new_sheet, alive=True ) user_sheet.save() return jsonify(ok=True, objects=[ new_sheet.to_json() ]), 201
def add_to_database(idx: str, client_id: str, email: str, token: int): try: db.session.add( Auth(idx=idx, client_id=client_id, email=email, token=token)) db.session.commit() except IntegrityError: add_to_database(idx, client_id, email, token)
def test_registration_with_invalid_data(): auth = Auth.Auth() data_copy = dict(TEST_USER_DATA) data_copy.update({"email": 123}) password = 123 with pytest.raises(Exception): auth.register(data_copy, password)
def test_register(): user = User.User() res = user.create(TEST_USER_DATA) auth = Auth.Auth() password = "******" api_token = auth.register(res["user_id"], password) TEST_USER_DATA.update({"user_id": res["user_id"]}) assert api_token is not None
def profile(self): ''' get the profile of the currently authenticated user ''' try: user = Auth.getUser() # @Todo rename this to getLoggedInUser() return jsonify(ok=True, objects=[user.to_json()]), 200 except: # @Todo pass abort(500)
def auth_add(): form = AuthForm() if form.validate_on_submit(): data = form.data auth = Auth(name=data['name'], url=data['url']) db.session.add(auth) db.session.commit() flash('权限添加成功', 'ok') return render_template('admin/auth_add.html', form=form)
def get(self, id): """ Get Sheet document with given id if user is allowed """ user = Auth.getUser() #try: sheet = Sheet.objects.get(id=id) #check if the user has privileges to view this sheet user_sheet = UserSheet.objects.get(sheet=sheet, user=user, alive=True) if (user_sheet): return jsonify(ok=True, objects=[user_sheet.to_json()]), 200
def get (self, id): """ Get Sheet document with given id if user is allowed """ user = Auth.getUser() #try: sheet = Sheet.objects.get(id=id) #check if the user has privileges to view this sheet user_sheet = UserSheet.objects.get(sheet=sheet, user=user, alive=True) if (user_sheet) : return jsonify(ok=True, objects=[user_sheet.to_json()]), 200
def refresh(request_body): try: token = request_body.get("token") user_id = request_body.get("user_id") data = Auth.Auth().refresh_api_token(token, user_id) if token is None: return make_response({"message": "Unauthorized"}, 401) return make_response({"token": data, "message": "Success"}, 200) except Exception as e: return make_response({"message": str(e)}, 500)
def setup(**kwargs): if Auth().is_user_logged_in(): Rich().rich_print(":thumbs_up: Hip Hip Hooray, Everything Is Set Up!") return True answer = Questionary().ask_selection_question( "🔎 Oh, You Are Not Logged In, You Want To ", ["Create A New Account.", "Log-in To My Account."]) if "Log-in" in answer: return CLI().login_cli() else: return CLI().signup_cli()
def login(request_body): try: email = request_body.get("email") password = request_body.get("password") data = Auth.Auth().login(email, password) if data is None: return make_response({"message": "No such user with email " + "'" + email + "'"}, 400) if not data: return make_response({"message": "Incorrect password"}, 401) return make_response({"data": data, "message": "Success"}, 200) except Exception as e: return make_response({"message": str(e)}, 500)
def post(self): if not request.json or 'name' not in request.json: abort(400) user = User.objects(email=request.json['email']) if len(user) > 0: return jsonify( ok=False, errors=['Email already in use. Account creation failed']), 403 new_user = User(name=request.json['name'], email=request.json['email'], alive=True) new_user.description = request.json.get('description', None) new_user.location = request.json.get('location', None) new_user.phone = request.json.get('phone', None) new_user.public = True new_user.save() if 'password' in request.json: auth = Auth(user=new_user, password=request.json['password'], alive=False) auth.password = auth.hash_password(request.json['email'], request.json['password']) auth.save() return jsonify(ok=True, objects=[new_user.to_json()]), 201
def sign_up(): name = request.form.get('name') surname = request.form.get('surname') email = request.form.get('email') password = request.form.get('password') phone = request.form.get('phone') second_phone = request.form.get('second_phone') location = request.form.get('location') if name == '': abort(422) if surname == '': abort(422) if email == '': abort(422) if password == '': abort(422) if location == "hojakent": location = 1 elif location == "gazalkent": location = 2 hashed = hashlib.md5(password.encode()).hexdigest() log_ins = Auth(name=name, surname=surname, email=email, password=hashed, phone=phone, second_phone=second_phone, locations=location, image_link=None, permission=None) log_ins.insert() return redirect(url_for('home'))
def register(request_body): try: # Create user user_data = request_body.get("user_data") password = request_body.get("password") new_user = User.User().create(user_data) # If new user could not be created, the request data was bad if new_user is None: return make_response({"message": "Bad request"}, 400) # Register newly created user token = Auth.Auth().register(new_user["user_id"], password) return make_response({"token": token, "user_id": new_user["user_id"], "message": "Success"}, 200) except Exception as e: return make_response({"message": str(e)}, 500)
def login(): if not request.json or not 'log_email' in request.json or not 'log_pass': return jsonify({'status': 'error', 'result':'Error reading values. Please try again'}) else: usr = User.query.filter_by(email = request.json['log_email']).first() if not usr is None: if str(usr.password) != str(request.json['log_pass']): return jsonify({'status': 'error', 'result':'Incorrect password'}) else: nuser = Auth(user_id=usr.id) db.session.add(nuser) db.session.commit() atk = str(nuser.id) + '._brk.' return jsonify({'status': 'ok', 'result': 'success', 'auth_token':atk}) else: return jsonify({'status': 'error', 'result':'User does not exists!'})
def auth_add(): form = AuthForm() if form.validate_on_submit(): data = form.data auth = Auth(name=data["name"], url=data["url"]) db.session.add(auth) db.session.commit() flash("添加权限成功!", "ok") oplog = Oplog( admin_id=session["admin_id"], ip=request.remote_addr, reason="添加权限%s" % data["name"], ) db.session.add(oplog) # 操作日志 db.session.commit() return render_template("admin/auth_add.html", form=form)
def post (self): if not request.json : abort(400) email = request.json.get('email', None) password = request.json.get('password', None) if email == None or password == None : abort(400) ''' check authentication ''' try: user = User.objects.get(email=email) password = Auth.hash_password(user.email, password) auth = Auth.objects.get(user=user, password=password) ''' setup a new session ''' _session = Session(auth_id=str(auth.id),alive=True) _session.save() auth.sessions.append( _session ) auth.alive = True auth.hash = str(auth.id) + str(_session.id) auth.save() response = make_response(jsonify(ok=True), 200 ) response.set_cookie('yearplan_user', value=auth.hash) response.headers['X-yearplan-user'] = auth.hash return response except: pass return jsonify(ok=False,objects=['Invalid email and password combination']), 401
def post(self): """ Create a Sheet with given JSON """ user = Auth.getUser() new_sheet = Sheet( name=request.json['name'], description=request.json['description'], #location = request.json.get('location',None), public=request.json.get('public', True), links=request.json.get('links', []), color=request.json.get('color', None), tags=request.json.get('tags', None)) new_sheet.created_by = user new_sheet.alive = True new_sheet.save() # connect the user to the new sheet user_sheet = UserSheet(name=new_sheet.name, user=user, sheet=new_sheet, alive=True) user_sheet.save() return jsonify(ok=True, objects=[new_sheet.to_json()]), 201
def put(self, id): """ Update a user's details """ user = User.objects.get_or_404(id=id) #prevent non authorised users from editing other user's details _currentUser = Auth.getUser() if _currentUser != user: abort(401) if 'user' in request.json: # save the old details in history user.history.append(user) user.name = request.json['user']['name'] user.description = request.json['user']['description'] user.location = request.json['user']['location'] user.phone = request.json['user']['phone'] user.links = request.json['user'].get('links', []) user.alive = True user.save() # create an Auth account if it doesn't exist or # update the password if it does if 'password' in request.json['user']: try: auth = Auth.objects.get(user=user) except (Exception): auth = Auth(user=user, password=request.json['user']['password'], alive=True) auth.password = Auth.hash_password(user.email, auth.password) auth.save() return jsonify(ok=True), 200 abort(401)
def put(self, id): """ Update a user's details """ user = User.objects.get_or_404(id=id) #prevent non authorised users from editing other user's details _currentUser = Auth.getUser() if _currentUser != user : abort(401) if 'user' in request.json: # save the old details in history user.history.append( user ) user.name = request.json['user']['name'] user.description = request.json['user']['description'] user.location = request.json['user']['location'] user.phone = request.json['user']['phone'] user.links = request.json['user'].get('links', []) user.alive = True user.save() # create an Auth account if it doesn't exist or # update the password if it does if 'password' in request.json['user'] : try: auth = Auth.objects.get(user=user) except(Exception): auth = Auth(user=user, password=request.json['user']['password'], alive=True ) auth.password = Auth.hash_password(user.email, auth.password) auth.save() return jsonify(ok=True),200 abort(401)
def test_refresh_api_token(): auth = Auth.Auth() api_token = auth.login(TEST_USER_DATA["email"], "password")["token"] new_token = auth.refresh_api_token(api_token, TEST_USER_DATA["user_id"]) assert new_token is not None
def test_instantiation(): auth = Auth.Auth()
def signout(**kwargs): if Auth().is_user_logged_in(): Files().remove_api_key() Rich().rich_print("🥺 You Now Logged-Out! Hope To See You Soon...") else: Rich().rich_print("😧 You Were Not Logged-In!")
def test_login(): auth = Auth.Auth() api_token = auth.login(TEST_USER_DATA["email"], "password") assert api_token is not None
def test_login_with_incorrect_password(): auth = Auth.Auth() assert auth.login(TEST_USER_DATA["email"], "incorrect password") == False
def authenticate(username, password): auth = Auth.getRecordByEmail(email=username) if auth.password == hashlib.sha256( password.encode('utf-8')).hexdigest(): return auth
def create(username, password): """ Create a new auth """ auth = Auth(username=username, password=password) return auth.save()
def __init__(self): self.__auth = Auth.Auth()
def test_login_with_incorrect_email(): auth = Auth.Auth() assert auth.login("*****@*****.**", "password") is None
def test_register_user_already_exists(): auth = Auth.Auth() password = "******" with pytest.raises(Exception): auth.register(TEST_USER_DATA["user_id"], password) User.User().delete(TEST_USER_DATA["user_id"])