def register_member(data): member = Member(first_name=data['first_name'], last_name=data['last_name'], email=data['email'], patronymic=data['patronymic'], phone_number=data['phone_number'], role_id=data['role'], swimming_skill=data['swimming_skill'], password=func.Hash(data['password']), take_part_flag=data['take_part_flag']) try: member.save() token = Token(user_id=member.id, token=secrets.token_hex(51)) token.save() return HttpResponse(renderers.JSONRenderer().render({ 'member_id': member.id, 'auth_token': token.token })) except Exception as e: return HttpResponse(renderers.JSONRenderer().render({ 'status': '0', 'error': type(e) }))
def get(self, request): credentials = twitter.Api().GetAppOnlyAuthToken( os.environ['CONSUMER_KEY'], os.environ['CONSUMER_SECRET']) token = Token(token_type=credentials['token_type'], access_token=credentials['access_token']) token.save() return Response(credentials)
def post(self): """Function handling reset password api endpoint""" try: identity = get_jwt_identity() jti = get_raw_jwt()['jti'] current_user = User.get_user_by_username(identity) data = request.get_json(self) # if validate_reset_password(data): # return validate_reset_password(data) if User.verify_password(current_user.password_hash, data["password"]): try: current_user.password_hash = current_user.hash_password(data['new_password']) current_user.save() except: pass finally: # Revoke token after password change Revoked(jti).save() Token.delete(Token.token_by_owner(current_user)) return Response(json.dumps({"Message": "Password updated successfully. Please login again."}), status=200) return Response(json.dumps({"Message": "Password do not match"}), status=403) except Exception as e: print(e) return Response(json.dumps({"Message": "Not logged in"}), status=401)
def login(request): if request.method == "POST": info = loads(request.body.decode('utf-8')) try: phone = info['phone'] user = User.objects.filter(phone=phone) if user.exists(): password = info['password'] if user[0].password == password: Device(dev_id=info['deviceId'], reg_id=info['deviceToken'], name=phone, is_active=True).save() user.update(status=True) tok = get_random_string(length=32) tok = Token(user=user[0], token=tok, expiry_date=datetime.datetime.now()) tok.save(force_insert=True) return my_response(True, 'success', tok.to_json()) else: return my_response(False, 'invalid information', {}) else: return my_response(False, 'user not found', {}) except Exception as e: e = str(e) if e.__contains__('UNIQUE constraint'): Device.objects.filter(dev_id=info['deviceId']).delete() return login(request) return my_response(False, 'error in login, check login body, ' + e, {}) else: return my_response(False, 'invalid method', {})
def post(self): """Function handling logout user api endpoint""" try: current_user = get_jwt_identity() jti = get_raw_jwt()['jti'] if not Revoked.is_blacklisted(jti): Revoked(jti).save() Token.delete(Token.token_by_owner(current_user)) return Response(json.dumps({"Message": "Logged out successfully"}), status=200) return Response(json.dumps({"Message": "User token has been revoked"}), status=403) except Exception as e: print (e) return Response(json.dumps({"Message": "Not logged in"}), status=401)
def load_token(): tokens = Token.objects.filter(ts__gte=ts()) if len(tokens) == 0: settings = T411_SETTINGS try: t411 = T411(settings) except Exception as e: raise e t = Token(token=t411.token, ts=ts() + 3600 * 24 * 90) t.save() token = t411.token else: token = tokens[0].token return token
def create(self, request, format=None): # リクエストボディのJSONを読み込み、メールアドレス、パスワードを取得 try: data = json.loads(request.body) email = data['email'] password = data['password'] except: # JSONの読み込みに失敗 return JsonResponse({'message': 'Post data injustice'}, status=400) # メールアドレスからユーザを取得 if not User.objects.filter(email=email).exists(): # 存在しない場合は403を返却 return JsonResponse({'message': 'The email is wrong.'}, status=403) user = User.objects.get(email=email) # パスワードチェック if not user.check_password(password): # チェックエラー return JsonResponse({'message': 'The password is incorrect'}, status=401) # ログインOKの場合は、トークンを生成 token = Token.create(user) # トークンを返却 return JsonResponse({'token': token.token}, status=201)
def authenticate(self, request): authorization = request.META.get("HTTP_AUTHORIZATION", None) if not authorization or not authorization.startswith("Bearer"): return None token = authorization.split(" ")[-1] role = UserRole.User.name.lower() if token == SUPER_USER_TOKEN: username = ADMIN_NAME user_model, _ = UserModel.objects.get_or_create(name=username) else: try: token_model = Token.objects.get(token=token, expire_date__gt=timezone.now()) except ObjectDoesNotExist: try: token_info = keycloak_openid.introspect(token) active = token_info.get("active", False) role = token_info.get("role", UserRole.User.name.lower()) exp_time = timezone.make_aware( datetime.fromtimestamp(token_info.get("exp"))) username = token_info.get("preferred_username", "") sub = token_info.get("sub", "") if not active: return None except Exception as exc: LOG.error("exception %s", str(exc)) return None user_model, _ = UserModel.objects.get_or_create(id=sub, name=username) user_model.role = role user_model.save() token_model = Token(token=token, user=user_model, expire_date=exp_time) token_model.save() else: username = token_model.user.name user_model = token_model.user role = user_model.role user = User() user.username = username user.token = token user.role = role user.user_model = user_model return user, None
def register(request): if request.method == "POST": try: info = loads(request.body.decode('utf-8')) p = info['phone'] e = info['email'] this_otp = info['otp'] o = Otp.objects.get(email=e) if o.otp != this_otp: return my_response(False, 'confirmation code invalid', None) if time_diff(get_hour_minute(), o.expiry) > 5: o.delete() return my_response( False, 'confirmation code invalid, try from first', None) user = User( phone=p, email=e, name=info['name'], password=info['password'], ) user.save(force_insert=True) tok = get_random_string(length=32) tok = Token(user=user, token=tok, expiry_date=datetime.datetime.now()) tok.save(force_insert=True) o.delete() Device(dev_id=info['deviceId'], reg_id=info['deviceToken'], name=p, is_active=True).save() return my_response(True, 'user registered', tok.to_json()) except Exception as e: e = str(e) if e.__contains__('UNIQUE constraint'): return my_response(False, 'user exist! please sign in', {}) else: return my_response(False, 'error in register, check body send, ' + e, {}) else: return my_response(False, 'invalid method', {})
def post(self): """Function serving login user api endpoint""" data = request.get_json(self) data['username'] = data['username'].replace(" ", "").lower() if validate_login(data): return Response(json.dumps(validate_login(data)), status=400) user = User.query.filter_by(username=data['username']).first() if user: if User.verify_password(user.password_hash, data['password']): logged_in = Token.token_by_owner(user.username) # if logged_in: # return Response(json.dumps({"Message": "Already logged in", "Token": logged_in.token}), status=403) expires = timedelta(days=30) token = create_access_token(identity=user.username, expires_delta=expires) tk = Token(token, user.username).save() return Response(json.dumps({"Message": "Successfully logged in", "Token": token, "User": user.serialize}), status=200) return Response(json.dumps({"Message": "Wrong password"}), status=401) return Response(json.dumps({"Message": "User does not exist"}), status=404)
def setUp(self): """ setUp for testing """ User.objects.create(username='******', email='*****@*****.**', profile='user1', password='******') self.user1 = User.objects.get(username='******') self.token1 = Token.create(self.user1)
def handle(self, *args, **options): username = options['email'] try: u = User.objects.get(email=username) except User.DoesNotExist: raise CommandError("user '%s' does not exist" % username) token = Token.new_token(u) self.stdout.write(f'New Token for %s is: %s' % (username, token.key))
def setUp(self): """ setUp for testing """ User.objects.create(username='******', email='*****@*****.**', profile='user1', password='******') User.objects.create(username='******', email='*****@*****.**', profile='user2', password='******') self.user1 = User.objects.get(username='******') self.token1 = Token.create(self.user1) self.user2 = User.objects.get(username='******') self.token2 = Token.create(self.user2) date = timezone.now() # user1の投稿 self.post1 = Post.objects.create(user_id=self.token1.user_id, body='test1', status='public', created_at=date, updated_at=date) self.post2 = Post.objects.create(user_id=self.token1.user_id, body='test2', status='public', created_at=date, updated_at=date) # user2の投稿 self.post3 = Post.objects.create(user_id=self.token2.user_id, body='test3', status='public', created_at=date, updated_at=date) self.post4 = Post.objects.create(user_id=self.token2.user_id, body='test4', status='public', created_at=date, updated_at=date)
def signup(request): username = request.POST.get('username') password = request.POST.get('password') fname = request.POST.get('fname') lname = request.POST.get('lname') encode = jwt.encode({'username': username}, settings.SECRET_KEY) if User.objects.filter(username=username).exists(): response = {'result': -1, 'message': 'User name exist'} else: try: user = User(username=username, password=password, first_name=fname, last_name=lname) user.set_password(password) user.is_active = True user.is_staff = True user.is_superuser = True group_name = 'admin' try: group = Group.objects.get(name=group_name) except Group.DoesNotExist: new_group, created = Group.objects.get_or_create( name=group_name) group = Group.objects.get(name=group_name) user.save() group.user_set.add(user) token = Token(user=user, token=str(encode)) token.save() response = {'result': 1, 'message': 'Save success'} except Exception as e: response = {'result': 0, 'message': 'Can not save user'} return JsonResponse(response)
def setUp(self): """ setUp for testing """ self.BASE_DIR = path.dirname(path.dirname(path.abspath(__file__))) User.objects.create(username='******', email='*****@*****.**', profile='user', password='******') self.user = User.objects.get(username='******') self.token = Token.create(self.user) date = timezone.now() # 投稿 self.post = Post.objects.create(user_id=self.token.user_id, body='test', status='public', created_at=date, updated_at=date)
def create(self, request): # tokenの確認 authorization = self.check_authorization() if authorization: # tokenがなかったり違っていたらJSONレスポンスを返す return authorization # ユーザーが存在するかの確認 if not User.objects.filter(id=self.token.user_id).exists(): # 存在しない場合は403を返却 return JsonResponse({'message': 'User does not exist'}, status=403) # ユーザーの情報取得 user = User.objects.get(id=self.token.user_id) # ログアウトがokならトークンをNoneにis_loginをFalseにする token = Token.logout(user) # ログアウトの結果をレスポンスで返す result = { 'user_id': token.user_id, 'is_login': token.is_login, } return JsonResponse(result, status=201)
def auth(): if user_obj.check_password(user_obj.password, password): token_dict = { "key": getRandomString(32), "user_id": user_obj.nid } # token 时效性一周 if Token.uget(user_obj.nid): Token.uupdate(user_obj.nid, token_dict) else: token_obj = Token(**token_dict) token_obj.add() # 登录成功初始化状态 1 错误次数 0 User.update(user_obj.nid, {"status": 1, "errtimes": 0}) res.data = { "username": username, "token": token_dict.get("key") } return res.dict # 错误次数达到3次 锁定账号 elif user_obj.errtimes == trytimes: User.update(user_obj.nid, {"status": 0, "locktime": newtime}) return dict(errcode=4022, errmsg="错误次数过多,账号已锁定,请%s分钟后重试" % lockmin) else: # 错误次数+1 User.updateplus(user_obj.nid) if user_obj.errtimes == trytimes: User.update(user_obj.nid, { "status": 0, "locktime": newtime }) return dict(errcode=4022, errmsg="错误次数过多,账号已锁定,请%s分钟后重试" % lockmin) else: return dict(errcode=4021, errmsg="密码错误,还可尝试%s次,错误3次账号将锁定5分钟" % (trytimes - user_obj.errtimes))
def token_add(request): if request.method == 'POST': f = ApiTokenForm(request.POST) if f.is_valid(): cleaned_data = f.cleaned_data try: token = Token() token.title = cleaned_data['title'] token.token = cleaned_data['token'] token.save() messages.info(request, '添加成功') except: messages.error(request, '添加失败') finally: return redirect('admin:api.token') else: f = ApiTokenForm() return render(request, 'admin/api/add_token.html', { "form": f, "auto_generate_token": uuid4(), })
def add_token(self): # assign a token to the user t = Token(user=self, daily_computation_time=600) t.token = t.generate_token(self.email) t.save()