def sms_user_activate(request): """ @api {post} /authe/sms_activate/ Sms activation method @apiName sms_user_activate @apiGroup Authe @apiHeader {String} Csrf-Token CSRF token. @apiParam {String} phone Phone of user. @apiParam {Number} code Code sent to user. @apiSuccess {Object} Json with code """ phone = request.POST["phone"] code = request.POST["code"] now = timezone.now() try: activation = Activation.objects.get(code=code, username=phone, is_active=True) except: return http.code_response(code=codes.ACTIVATION_CODE_NOT_FOUND, message=messages.ACTIVATION_CODE_NOT_FOUND) if activation.end_time < now: return http.code_response(code=codes.ACTIVATION_TIME_EXPIRED, message=messages.ACTIVATION_TIME_EXPIRED) activation.is_active = False activation.save() user, _ = User.objects.get_or_create(username=phone) user.is_active = True user.phone = phone user.set_password(activation.code) user.user_type = TELEPHONE_REGISTER user.save() UserStat.objects.add_stat(request, user.id, user_created=True) return {"token": token.create_token(user), "user": user.full()}
def login(): ''' 登陆请求 @@@ ### 说明 登陆请求 ### 请求 | 字段 | 字段类型 | 可选/必选 | 字段描述 | | username | string | M | 登陆用户名 | | password | string | M | 密码 | ### 返回 | 字段 | 字段类型 | 字段描述 | @@@ ''' username = g.args.get('username', None) password = g.args.get('password', None) if username is None or password is None: return make_response(code=1, msg='用户名或密码非法') res = dbse.query(User).filter(User.name == username).first() if res is None: return make_response(code=1, msg='用户不存在') if res.name == username and res.password == password: token = create_token({'userid': res.id, 'username': res.name}) return make_response(code=0, data={'token': token}) else: return make_response(code=1, msg='用户名或密码错误')
def login(request): """ """ try: username = request.POST.get("username").lower() password = request.POST.get("password") user = None try: validate_email(username) user = User.objects.filter(username=username).first() except: return http.code_response(code=codes.INVALID_USERNAME, message=messages.INVALID_USERNAME) if user is None: return http.code_response(code=codes.USERNAME_NOT_FOUND, message=messages.USER_NOT_FOUND) user = authenticate(username=user.username, password=password) if user is None: return http.code_response( code=codes.INCORRECT_USERNAME_OR_PASSWORD, message=messages.INCORRECT_USERNAME_OR_PASSWORD) user.timestamp = time_utils.get_timestamp_in_milli() user.save() return {'token': token.create_token(user), 'user': user.full()} except Exception as e: return http.code_response(codes.SERVER_ERROR, message=str(e))
def test_token_auth(username, password, email, create_token): ''' Create a user, get the token and verify it ''' client = Client() token = create_token(is_superuser=True) result = client.post( '/graphql?query=mutation{createUser(username: "******", password: "******", email: "' + email + '", isSuperuser: false' '){user{id, username}}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 token = client.post( '/graphql?query=mutation{tokenAuth(username: "******", password: "******"){token}}') assert token.status_code == 200 result_token = token.json()['data']['tokenAuth']['token'] verify = client.post( '/graphql?query=mutation{verifyToken' '(token: "' + result_token + '"){payload}}') assert verify.status_code == 200 assert verify.json()[ 'data']['verifyToken']['payload']['username'] == username
def get_token(self): user, _ = User.objects.get_or_create(username=TEST_USERNAME) user.set_password(TEST_PASSWORD) user.is_active = True user.save() self.token = token.create_token(user) return user
def phone_login_complete(request): valid, phone = valid_phone(request.POST["phone"]) if not valid: return http.code_response(code=codes.BAD_REQUEST, message=u"Неверный формат телефона") try: activation = Activation.objects.filter(phone=phone, code=request.POST.get( 'code', ''), used=False)[0] except: return http.code_response(code=codes.BAD_REQUEST, message=u"Неверный ключ активации") u, _ = User.objects.get_or_create(email=activation.phone) if not u.tariff_date: u.tariff_date = timezone.now().date() + timedelta(days=0) u.tariff = User.DEMO u.save() activation.used = True activation.save() try: email.delay( settings.ADMINS_LIST, u"Новый пользователь #{}".format(u.phone), u"Новый пользователь под номером {} и ID {}".format(u.phone, u.pk)) except: pass return {'token': token.create_token(u), 'user': u.json()}
def sign_in(request): """ @apiDescription Вход с помощью номера телефона/почты/социальной сети и пароля. @apiGroup 01. Core @api {post} /core/sign_in/ 01. Вход в систему [sign_in] @apiName Sign in @apiDescription Авторизация через `email` или `номер телефона` @apiParam {String} username email or phone number @apiParam {String} password Password @apiSuccess {json} result Json """ username = request.POST.get("username") password = request.POST.get("password") if valid_email(username): user = authenticate(request, email=username, password=password) else: phone = format_phone(username) user = authenticate(request, phone=phone, password=password) if user: ##################################################### # save last login time. Hard code. Fix Later from core models. from django.utils import timezone user.last_login = timezone.now() user.save() ##################################################### return { 'token': token.create_token(user, remove_others=True), 'user': user.json(user=user) } return http.code_response(code=codes.BAD_REQUEST, message=messages.WRONG_USERNAME_OR_PASSWORD)
def test_create_config(create_token): ''' This test create an object on db using a post request, require the saved object by graphql, and check if the requirement is equal the saved object ''' token = create_token() create = CLIENT.post( '/graphql?query=mutation{createConfig' '(number: 10, ' 'timeBetweenCycles: 20, ' 'upperLimit: 32, ' 'inferiorLimit: 16, ' 'upperTime: 5, ' 'inferiorTime: 5, ' 'disableShutdown: true, ' 'enableOutput: false, ' 'temperature: 64, ' 'name: "teste", ' 'time: 51)' '{config{number, timeBetweenCycles,upperLimit,inferiorLimit,' 'upperTime, inferiorTime, disableShutdown,' 'enableOutput, temperature,name, isDefault, time}}}', HTTP_AUTHORIZATION=token) assert create.status_code == 200 result = CLIENT.get( '/graphql?query=query{configAt(id: 1){number, timeBetweenCycles,' ' upperLimit, inferiorLimit, upperTime, inferiorTime,' 'disableShutdown, enableOutput, temperature, name, isDefault,time}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 assert create.json()['data']['createConfig']['config'] == result.json( )['data']['configAt']
def __init__(self, username, password, email, *args, **kwargs): self.name = username self.passwd = User.create_password(password) self.email = email.lower() self.token = create_token(16) for k, v in kwargs.iteritems(): setattr(self, k, v)
def get_token_and_user(self): user = MainUser.objects.create_superuser( username=TEST_USERNAME_MODERATOR, password=TEST_PASSWORD) user_info = {} user_info['token'] = token.create_token(user) user_info['user'] = user return user_info
def sign_up_complete(request): """ @apiDescription Завершение регистрации. Полсе подтверждения высланного кода, регистрация считается завершенной, и только после этого пользователь числится в базе. @api {post} /core/sign_up_complete/ 03. Завершение регистрации [sign_up_complete] @apiName Sign Up Complete @apiGroup 01. Core @apiParam {String} username Registration phone or email @apiParam {String} code Code sent to phone or email @apiSuccess {json} result Json """ username = request.POST.get("username") code = request.POST.get("code") if valid_email(username): if User.objects.filter(email=username).exists(): # Check if user with such email already signed up. return http.code_response(code=codes.BAD_REQUEST, message=messages.USER_ALREADY_EXISTS) try: activation = Activation.objects.filter(email=username, to_reset=False, to_change_phone=False, to_change_email=False, code=code, used=False)[0] except: return http.code_response( code=codes.BAD_REQUEST, message=messages.WRONG_ACTIVATION_KEY_OR_INVALID_EMAIL) u, _ = User.objects.get_or_create(email=activation.email) else: phone = format_phone(username) if User.objects.filter(phone=username).exists(): # Check if user with such phone already signed up. return http.code_response(code=codes.BAD_REQUEST, message=messages.USER_ALREADY_EXISTS) try: activation = Activation.objects.filter(phone=phone, to_reset=False, to_change_phone=False, to_change_email=False, code=code, used=False)[0] except: return http.code_response( code=codes.BAD_REQUEST, message=messages.WRONG_ACTIVATION_KEY_OR_INVALID_PHONE) u, _ = User.objects.get_or_create(phone=activation.phone) sign_up_user_complete(user=u, activation=activation) return { 'token': token.create_token(u, remove_others=True), 'user': u.json(user=u) }
def test_calibration_commands(create_token): ''' This test save a CalibrationCommand object on db, require the saved object by graphql, and check if the requirement is equal the saved object ''' token = create_token() response = { 'commandChanelSpeed': 7, 'actualSpeed': 0.000, 'maxSpeed': 100.000, 'chanelCommandPression': 8, 'actualPression': 0.000, 'maxPression': 30.000 } CalibrationCommand( command_chanel_speed=7, actual_speed=0.000, max_speed=100.000, chanel_command_pression=8, actual_pression=0.000, max_pression=30.000, ).save() CalibrationCommand( command_chanel_speed=6, actual_speed=1.000, max_speed=101.000, chanel_command_pression=9, actual_pression=1.000, max_pression=31.000, ).save() client = Client() result_single = client.get( '/graphql?query={calibrationCommand(id: 1)' '{commandChanelSpeed,actualSpeed,maxSpeed,' 'chanelCommandPression,actualPression,maxPression}}', HTTP_AUTHORIZATION=token) assert result_single.status_code == 200 single_aux = result_single.json()['data']['calibrationCommand'] single_calibration_commands = single_aux result_multiple = client.get( '/graphql?query={allCalibrationCommand' '{id,commandChanelSpeed,actualSpeed,maxSpeed,' 'chanelCommandPression,actualPression,maxPression}}', HTTP_AUTHORIZATION=token) assert result_multiple.status_code == 200 multiple_aux = result_multiple.json()['data']['allCalibrationCommand'] multiple_calibration_commands_1 = multiple_aux[1] assert multiple_calibration_commands_1['id'] == '2' assert single_calibration_commands == response
def get(self, organization, member, gist): private = create_token(20) if gist.private else None fork_gist, err = create_gist(organization, g.current_user, gist.summary, parent=gist, private=private, watchers=1) if err: return redirect(gist.meta.view) return redirect(get_url(organization, fork_gist))
def post(self): email = request.form.get('email', None) if not check_email(email): return self.render_template(error=code.ACCOUNT_EMAIL_INVAILD) user = get_user_by_email(email=email) if user: stub = create_token(20) forget, error = create_forget(user.id, stub) if error: return self.render_template(error=error) send_forget_mail(user, forget) return self.render_template(send=code.ACCOUNT_EMAIL_FORGET)
def post(self, request): data = json.loads(request.body) username = data.get("username", None) password = data.get("password", None) email = data.get("email", None) try: user = User.objects.create_user(username=username, password=password, email=email) token = create_token(user.username) return JsonResponse({"code": "0000", "msg": "注册成功", "data": token}) except: return JsonResponse({"code": "9999", "msg": "注册失败", "data": None})
async def token_create( username: UsernameType = Form(...), password: PasswordType = Form(...), ) -> TokenView: user = await User.query.where(User.username == username).gino.first() if user is None or not verify_password(password, user.hashed_password): raise HTTPException( status_code=403, detail='Wrong user or password', ) return TokenView( access_token=create_token(username, settings.jwt_lifetime_seconds), token_type='bearer', )
def test_mutation_force(create_token): ''' This function create a force calibration using the graphene mutation end check if the return of graphene is equal to the parameters used to create it ''' token = create_token() url = ('/graphql?query=mutation' '{createForce(' + stringfy(RESPONSE_FIRST_FORCE) + ')' '{force{acquisitionChanel, conversionFactor, forceOffset}}}') create_first_force = CLIENT.post(url, HTTP_AUTHORIZATION=token) assert create_first_force.status_code == 200 response = create_first_force.json()['data']['createForce']['force'] assert response == RESPONSE_FIRST_FORCE
def post(self, request): data = json.loads(request.body) username = data.get("username", None) password = data.get("password", None) user = authenticate(username=username, password=password) if user: token = create_token(user.username) return JsonResponse({"code": "0000", "msg": "登录成功", "data": token}) else: return JsonResponse({ "code": "9999", "msg": "账号或密码错误", "data": None })
def post(self, request): img_id = request.data.get("id") email = request.data.get("email") password = request.data.get("pwd") validate_code = request.data.get("validate_code") try: img_obj = CaptchaStore.objects.filter(id=img_id)[0] except IndexError: return Response({ "code": 1007, "data": None, "message": "该验证码不存在!" }) try: if validate_code.lower() != img_obj.response: return Response({ "code": 1008, "data": None, "message": "验证码不正确!" }) if time() > img_obj.expiration.timestamp(): return Response({ "code": 1010, "data": None, "message": "验证码过期!" }) user = User.objects.filter(email=email)[0] if user.password != password: return Response({ "code": 1007, "data": None, "message": "邮箱或密码不正确!" }) except IndexError: return Response({ "code": 1007, "data": None, "message": "邮箱或密码不正确!" }) # 更新 登录时间 user.save() token = create_token({'email': email}, exp=60) return Response({ "code": 1009, 'data': { "token": token, "uid": user.id }, "message": None })
def test_mutation_speed(create_token): ''' This function create a speed calibration using the graphene mutation end check if the return of graphene is equal to the parameters used to create it ''' token = create_token() url = ('/graphql?query=mutation{createSpeed(' + stringfy(RESPONSE_SPEED) + ')' '{speed{acquisitionChanel, tireRadius}}}') create_speed = CLIENT.post(url, HTTP_AUTHORIZATION=token) assert create_speed.status_code == 200 response = create_speed.json()['data']['createSpeed']['speed'] assert response == RESPONSE_SPEED
def test_calibration_temperature(create_token): ''' This test save a CalibrationTemperature object on db, require the saved object by graphql, and check if the requirement is equal the saved object ''' token = create_token() response = { 'acquisitionChanel': 1, 'conversionFactor': 0.200, 'temperatureOffset': -1.2500 } CalibrationTemperature( acquisition_chanel=1, conversion_factor=0.200, temperature_offset=-1.2500, ).save() CalibrationTemperature( acquisition_chanel=2, conversion_factor=0.400, temperature_offset=-2.500, ).save() client = Client() result = client.get( '/graphql?query={calibrationTemperature(id: 1)' '{acquisitionChanel, conversionFactor, temperatureOffset}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 single_aux = result.json()['data']['calibrationTemperature'] single_calibration_temperature = single_aux client = None result = None client = Client() result = client.get( '/graphql?query={allCalibrationTemperature' '{id, acquisitionChanel, conversionFactor, temperatureOffset}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 multiple_aux = result.json()['data']['allCalibrationTemperature'] multiple_calibration_temperature_1 = multiple_aux[1] assert multiple_calibration_temperature_1['id'] == '2' assert single_calibration_temperature == response
def test_calibration_vibration(create_token): ''' This test save a CalibrationVibration object on db, require the saved object by graphql, and check if the requirement is equal the saved object ''' token = create_token() response = { 'acquisitionChanel': 6, 'conversionFactor': 1.00, 'vibrationOffset': 1.00 } CalibrationVibration( acquisition_chanel=6, conversion_factor=1.00, vibration_offset=1.00, ).save() CalibrationVibration( acquisition_chanel=7, conversion_factor=2.00, vibration_offset=2.00, ).save() client = Client() result = client.get( '/graphql?query={calibrationVibration(id: 1)' '{acquisitionChanel, conversionFactor, vibrationOffset}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 single_aux = result.json()['data']['calibrationVibration'] single_calibration_vibration = single_aux client = None result = None client = Client() result = client.get( '/graphql?query={allCalibrationVibration' '{id, acquisitionChanel, conversionFactor, vibrationOffset}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 multiple_aux = result.json()['data']['allCalibrationVibration'] multiple_calibration_vibration_1 = multiple_aux[1] assert multiple_calibration_vibration_1['id'] == '2' assert single_calibration_vibration == response
def test_mutation_command(create_token): ''' This function create a command calibration using the graphene mutation end check if the return of graphene is equal to the parameters used to create it ''' token = create_token() url = ('/graphql?query=mutation' '{createCommand(' + stringfy(RESPONSE_COMMAND) + ')' '{command{ commandChanelSpeed, actualSpeed, maxSpeed,' 'chanelCommandPression, actualPression, maxPression}}}') create_command = CLIENT.post(url, HTTP_AUTHORIZATION=token) assert create_command.status_code == 200 response = create_command.json()['data']['createCommand']['command'] assert response == RESPONSE_COMMAND
def test_mutation_vibration(create_token): ''' This function create a vibration calibration using the graphene mutation end check if the return of graphene is equal to the parameters used to create it ''' token = create_token() url = ( '/graphql?query=mutation' '{createVibration(' + stringfy(RESPONSE_VIBRATION) + ')' '{vibration{acquisitionChanel, conversionFactor, vibrationOffset}}}') create_vibration = CLIENT.post(url, HTTP_AUTHORIZATION=token) assert create_vibration.status_code == 200 response = create_vibration.json()['data']['createVibration']['vibration'] assert response == RESPONSE_VIBRATION
def social_authenticate(social_type, social_id, email=None, phone=None, full_name=""): user = None if social_type == "facebook": try: user = User.objects.get(fb_id=social_id) except: pass elif social_type == "insta": try: user = User.objects.get(insta_id=social_id) except: pass elif social_type == "vk": try: user = User.objects.get(vk_id=social_id) except: pass if not user: if email: try: user = User.objects.get(email=email) user.set_social_id(social_type, social_id) except: # User with email doesnt exist pass if phone: try: user = User.objects.get(phone=phone) user.set_social_id(social_type, social_id) except: # User with phone doesnt exist pass if user: return { 'exists': True, 'token': token.create_token(user, remove_others=True), 'user': user.json(user=user) } return { 'exists': False, 'email': email, 'full_name': full_name, 'phone': phone }
def reset_password_complete(request): """ @apiDescription Завершение сброса пароля. <br>Полсе подтверждения высланного кода, процесс считается завершенным. @api {post} /core/reset_password_complete/ 10. Завершение сброса пароля [reset_password_complete] @apiGroup 01. Core @apiParam {String} phone Phone or email @apiParam {String} code Code sent to phone or email @apiSuccess {json} result Json """ phone = format_phone(request.POST.get("phone")) try: if len(phone) >= 10: if User.objects.filter(phone__endswith=phone[-10:]).count() == 1: user = User.objects.filter(phone__endswith=phone[-10:])[0] else: user = User.objects.get(phone__iexact=phone) else: user = User.objects.get(phone__iexact=phone) except: return http.code_response(code=codes.BAD_REQUEST, message=messages.USER_NOT_FOUND) try: activation = Activation.objects.filter(phone=user.phone, to_reset=True, to_change_phone=False, code=request.POST.get("code"), used=False)[0] except: return http.code_response(code=codes.BAD_REQUEST, message=messages.WRONG_ACTIVATION_KEY) user.password = activation.password user.save() activation.used = True activation.save() return { 'token': token.create_token(user, remove_others=True), 'user': user.json(user=user) }
def test_mutation_relations(create_token): ''' This function create a relations calibration using the graphene mutation end check if the return of graphene is equal to the parameters used to create it ''' token = create_token() url = ('/graphql?query=mutation' '{createRelations(' + stringfy(RESPONSE_RELATIONS) + ')' '{relations{transversalSelectionWidth, heigthWidthRelation,' 'rimDiameter, syncMotorRodation,' 'sheaveMoveDiameter, sheaveMotorDiameter}}}') create_relation = CLIENT.post(url, HTTP_AUTHORIZATION=token) assert create_relation.status_code == 200 response = create_relation.json()['data']['createRelations']['relations'] assert response == RESPONSE_RELATIONS
def test_config(create_token): ''' This test save a ConfigType object on db, require the saved object by graphql, and check if the requirement is equal the saved object ''' token = create_token() response = { 'number': 10, 'timeBetweenCycles': 20, 'upperLimit': 32, 'inferiorLimit': 16, 'upperTime': 5, 'inferiorTime': 5, 'disableShutdown': True, 'enableOutput': False, 'temperature': 64, 'time': 51, 'name': 'teste', 'isDefault': False, } Config( number=10, time_between_cycles=20, upper_limit=32, inferior_limit=16, upper_time=5, inferior_time=5, disable_shutdown=True, enable_output=False, temperature=64, time=51, name='teste', is_default=False, ).save() result = CLIENT.get( '/graphql?query={configAt(id: 1){number,timeBetweenCycles,upperLimit,' 'inferiorLimit, upperTime, inferiorTime,' 'disableShutdown, enableOutput, temperature,name, isDefault,time}}', HTTP_AUTHORIZATION=token) assert result.status_code == 200 assert result.json()['data']['configAt'] == response
def login(request): """ @api {post} /authe/login/ Login method @apiName login @apiGroup Authe @apiHeader {String} Csrf-Token CSRF token. @apiParam {String} username Username of user, must be an email. @apiParam {String} password Password of user, minimum length: 6. @apiSuccess {Object} result Json representation of user with token. """ try: username = request.POST.get("username").lower() password = request.POST.get("password") user = None try: validate_email(username) user = User.objects.filter(email=username).first() except: try: phone_object = phonenumbers.parse(username, None) if phonenumbers.is_valid_number(phone_object): user = User.objects.filter(phone=username).first() except: return http.code_response(code=codes.INVALID_USERNAME, message=messages.INVALID_USERNAME) if user is None: return http.code_response(code=codes.USERNAME_NOT_FOUND, message=messages.USER_NOT_FOUND) if not user.is_active: return http.code_response(code=codes.USER_NOT_VERIFIED, message=messages.USER_NOT_VERIFIED) user = authenticate(username=user.username, password=password) if user is None: return http.code_response( code=codes.INCORRECT_USERNAME_OR_PASSWORD, message=messages.INCORRECT_USERNAME_OR_PASSWORD) user.timestamp = time_utils.get_timestamp_in_milli() user.save() return {'token': token.create_token(user), 'user': user.full()} except Exception as e: logger.error(e) return http.code_response(codes.SERVER_ERROR, message=str(e))
def post(self): if request.form and 'cancel' in request.form: return redirect(url_for('index')) email = request.form.get('email', None) status = check_email(email) if status: return render_template('account.forget.html', error=status[1]) user = get_user_by_email(email=email) if user: stub = create_token(20) try: send_email(user.email, \ config.FORGET_EMAIL_TITLE, origin_render('email.html', user=user, stub=stub)) except: logger.exception("send mail failed") create_forget(user.id, stub) return render_template('account.forget.html', send=1)
def post(self, request): data = json.loads(request.body) username = data.get("username", None) password = data.get("password", None) user = authenticate(username=username, password=password) # 校验用户名和密码,成功返回user对象,失败返回None if user: token = create_token(user.username) return JsonResponse({ "code": "0000", "message": "登录成功", "data": token }) else: return JsonResponse({ "code": "9999", "message": "用户名或者密码不正确", "data": None })
def test_update_profile_phone_used(self): user, _ = User.objects.get_or_create(phone=TEST_PHONE) user.set_password(TEST_PASSWORD) user.is_active = True user.save() user1 = MainUser.objects.create_user(username=TEST_EMAIL, password=TEST_PASSWORD) user_token = token.create_token(user1) response = c.post('/api/authe/update_profile/', { AUTH_TOKEN_HEADER: user_token, 'phone': TEST_PHONE, 'full_name': 'Some Awesome Guy' }, HTTP_CSRF_TOKEN=token.generate_csrf('m')) self.common_test(response, status_code=STATUS_OK, code=codes.PHONE_USED)
def create_password(raw): salt = create_token(8) hsh = hashlib.sha1(salt + raw).hexdigest() return "%s$%s" % (salt, hsh)
def change_password(self, password): self.token = create_token(16) self.passwd = User.create_password(password) db.session.add(self) db.session.commit()