Beispiel #1
0
def create_auth_token(secret_key: str, data: dict, expiration=28800):
    """
    generate security token
    
    Args:
    * [secret_key] the secret key to encode
    * [data] the data which encapsulated to the token 
    * [expiration] out date time in seconds, default 60 x 60 x 8, set to 0 will be permanent available
    
    Returns:
    * [bytes] authorized token
    """
    # print(secret_key, "\n", data)

    if expiration > 0:
        security = serializer(secret_key=secret_key, expires_in=expiration)
    else:
        security = serializer(secret_key=secret_key)

    timestamp = ticker.time_since1970()
    iat = {"iat": timestamp}

    if data is None:
        return security.dumps(iat)
    else:
        ext = DictExtern.union(data, iat)
        return security.dumps(ext)
 def reset_password(token):
     s = serializer(app.config['SECRET_KEY'])
     try:
         user_id = s.loads(token)['user_id']
     except:
         return None
     return user_id
Beispiel #3
0
 def verifyResetToken(token):
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         user_id = s.loads(token)['user_id']
     except:
         return None
     return users.query.get(user_id)
Beispiel #4
0
def uservalidation(request, token):
    s = serializer(SECRET_KEY)
    try:
        email = s.loads(token)['email']
        name = s.loads(token)['name']
        phnumber = s.loads(token)['phnumber']
        password = s.loads(token)['password']
        user = User.objects.create_user(unique_username_id_generator(name),
                                        email, password)
        if len(name.split(' ')) >= 2:
            user.first_name = name.split(' ')[0]
            user.last_name = name.split(' ')[1]
            user.save()
        else:
            user.first_name = name
            user.save()

        obj = usersdetails(uid=unique_username_id_generator(name),
                           phnumber1=(phnumber),
                           users=user)
        obj.save()
        userwallet = wallet(walletid=unique_wallet_id_generator(name),
                            user=user,
                            userdetail=obj)
        userwallet.save()
        messages.success(request,
                         'Your Account has been created successfully.')
        return redirect('home')
    except:
        d = User.objects.filter(password='')
        for i in d:
            i.delete()
        return HttpResponse(
            '<h1>Your Verification link is expired plese sigup again</h1>')
Beispiel #5
0
def verify_auth_token(token: bytes, secret_key: str):
    """
    verify security token

    Args:
    * [token] the web token
    * [secret_key] the secret key to decode
    
    Returns:
    * [tunple(int, dict)] deserialized contains data in dict
    """
    security = serializer(secret_key=secret_key)

    # try to decode
    data = None
    try:
        data = security.loads(token)
        # token decode if failed, because time expired
    except SignatureExpired:
        #log.warning("TokenManager", "remote token expired", remoteip)
        return TOKEN_STATUS.SignatureExpiredError, None
    except BadSignature:
        #log.warning("TokenManager", "remote token has bad signature", remoteip)
        return TOKEN_STATUS.BadSignatureError, None
    except:
        #log.warning("TokenManager", "unkonw exception", remoteip)
        return TOKEN_STATUS.OtherError, None

    return TOKEN_STATUS.OK, data
Beispiel #6
0
 def check_token(token):
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         user = s.loads(token)['user_id']
     except:
         return None
     return User.query.get(user)
Beispiel #7
0
def register_logic(request):
    try:
        name=request.POST.get('user_name')
        pwd=request.POST.get('pwd')
        cpwd=request.POST.get('cpwd')
        email=request.POST.get('email')
        allow=request.POST.get('allow')
        #密码加盐
        salt=str(uuid.uuid4())
        ha=hashlib.sha256()
        new_pwd=pwd + salt
        ha.update(new_pwd.encode())
        rst=ha.hexdigest()
        if pwd==cpwd and allow:
            rst1=Users.objects.create(name=name,pwd=rst,email=email,salt=salt)
            if rst1:
                id=rst1.id
                ser=serializer(settings.SECRET_KEY,expires_in=180)
                s=ser.dumps({'id':id}).decode()
                try:
                    send_mail('账户激活','http://127.0.0.1:8000/userapp/active/?token='+s,'*****@*****.**',['*****@*****.**'])
                    return JsonResponse({'msg':'注册成功,请等待管理员激活账户','status':1})
                except:
                    return JsonResponse({'msg':'发送邮件失败','status':0})
            else:
                return JsonResponse({'msg':'注册失败','status':0})
    except:
        return JsonResponse({'msg':'注册失败','status':0})
Beispiel #8
0
def generate_verify_email_url(user):
    s = serializer(settings.SECRET_KEY,
                   expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id': user.id}
    token = s.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url
Beispiel #9
0
 def verify_reset_token(token):
     s = serializer(app.config['SECRET_KEY'])
     try:
         user_id = s.loads(token)['user_id']
     except:
         return None
     return User.query.get(user_id)
Beispiel #10
0
 def check_verify(token):
     s = serializer(app.config['SECRET_KEY'])
     try:
         userid = s.loads(token)["user_id"]
     except Exception as e:
         print(e)
         return None
     return User.query.get(userid)
 def get_reset_token(self, expires=1800):
     '''This function create and get a new passwrod reset token for user'''
     s_obj = serializer(app.config["SECRET_KEY"], expires)
     token = s_obj.dumps({
         'user_id': self.id,
         'utype': 'user'
     }).decode("utf-8")
     return token
Beispiel #12
0
 def confirm_token(self, token):
     s = serializer(current_app.config['SERCRET_KEY'])
     try:
         res = s.loads(token)
     except:
         return False
     if res.get('token_value') != self.id:
         return False
     return True
Beispiel #13
0
def give_token(email, firstname, lastname, password):
    s = serializer(SECRET_KEY, 1180)
    token = s.dumps({
        'email': email,
        'firstname': firstname,
        'lastname': lastname,
        'password': password
    }).decode('utf-8')
    return token
Beispiel #14
0
def give_token5(email, name, phnumber, password):
    s = serializer(SECRET_KEY, 11180)
    token = s.dumps({
        'email': email,
        'name': name,
        'phnumber': phnumber,
        'password': password
    }).decode('utf-8')
    return token
Beispiel #15
0
 def confirm(self, token):
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get('confirm') != self.id:
         return False
     self.confirmed = True
     db.session.add(self)
     return True
Beispiel #16
0
 def reset_password(token, new_password):
     s = serializer(current_app.config['SECURE_KEY'])
     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
Beispiel #17
0
 def reset_password(self, token, new_password):
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get('reset') != self.id:
         return False
     self.password = new_password
     db.session.add(self)
     return True
Beispiel #18
0
 def reset_password(token, new_password):
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token.encode('utf-8'))
     except:
         return False
     user = User.query.get(data['reset'])
     if user is None:
         return False
     user.password = new_password
     db.session.add(user)
     return True
Beispiel #19
0
    def post(self, request):
        """post请求方式"""
        # 1.接收数据
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        is_on = request.POST.get('allow')

        # 2.校验数据
        if not all([username, password, email]):
            return render(request, 'register.html', {'errormsg': '数据不完整'})
        # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',
                        email):
            return render(request, 'register.html', {'errormsg': '邮箱不合法'})
            # 校验勾选协议
        if is_on != 'on':
            return render(request, 'register.html', {'errormsg': '请勾选协议'})

        # 判断用户名是否已经存在,不存在的话抛出异常,接受异常判断不存在
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # 说明不存在
            user = None
        if user:
            return render(request, 'register.html', {'errormsg': '用户名已存在'})

        # 3.业务处理,用户注册,注册到user表中,可以手动创建注册,这里使用django默认的注册方法
        new_user = User.objects.create_user(username, email, password)
        # 刚刚注册完的用户先不激活
        new_user.is_active = 0
        new_user.save()

        # 加密用户身份信息,生成激活token
        ser = serializer(settings.SECRET_KEY, 3600)
        info = {'confirm': new_user.id}
        token = ser.dumps(info)
        token = token.decode()  # 默认解码utf8

        # 发送邮件
        subject = '%s天天生鲜欢迎您!' % username
        message = ''
        sender = settings.EMAIL_FROM
        receiver = [email]
        html_message = '点击下面链接激活<a href="http://127.0.0.1:8000/user/active/%s">激活...</a>' % token  # 这里面写html可以正确显示
        send_mail(subject,
                  message,
                  sender,
                  receiver,
                  html_message=html_message)
        # 4.返回页面
        return redirect(reverse('goods:index'))
Beispiel #20
0
 def confirm(self, token):
     """ 验证是否确认过注册邮件 """
     s = serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token.encode('utf8'))
     except Exception:
         return False
     if data.get('confirm') != self.id:
         return False
     self.confirmed = True
     db.session.add(self)
     return True
Beispiel #21
0
    def get(self, request, token):
        try:
            s = serializer(settings.SECRET_KEY, 300)
            info = s.loads(token)
            user_id = info['user_id']
            user = User.objects.get(id=user_id)

            return render(request, 'reset_pwd.html', {'username': user})
        except SignatureExpired as e:
            return HttpResponse('验证码已过期')
        except Exception as e:
            return render(request, '404.html')
Beispiel #22
0
def emailreset(request, token):
    s = serializer(SECRET_KEY)
    try:
        newemail = s.loads(token)['newemail']
        email = s.loads(token)['email']
        user = User.objects.filter(email=email).first()
        user.email = newemail
        user.save()
        messages.success(request, 'Your Email is changed  successfully.')
        return redirect('home')
    except:
        return HttpResponse('<h1>Your Email reseting  link is expired.</h1>')
 def verify_reset_token(token):
     '''This function verifies the token to be correct or not'''
     s_obj = serializer(app.config["SECRET_KEY"])
     try:
         # check if the we can get the user id and type from token or not
         user_id = s_obj.loads(token)['user_id']
         utype = s_obj.loads(token)['utype']
     except:
         # it means the token is not valid or expird if we dont get id from it
         return None
     data = {'user': UserModel.query.get(user_id), 'user_type': utype}
     return data
Beispiel #24
0
    def generate_auth_token(self, secret_key, expiration=600):
        """Generates a new token.

        Args:
            secret_key: The key to use to create the new token.
            expiration: The duration the token will be valid for.

        Return:
            A token.
        """
        s = serializer(secret_key, expires_in=expiration)
        return s.dumps({"id": self.id})
Beispiel #25
0
def reactive(request):
    try:
        name=request.GET.get('username')
        user=Users.objects.get(name=name)
        id=user.id
        print(id)
        ser = serializer(settings.SECRET_KEY, expires_in=180)
        s = ser.dumps({'id': id}).decode()
        send_mail('账户激活', 'http://127.0.0.1:8000/userapp/active/?token=' + s, '*****@*****.**', ['*****@*****.**'])
        return JsonResponse({'msg':'发送激活邮件成功','status':1})
    except:
        traceback.print_exc()
        return JsonResponse({'msg':'发送激活邮件失败','status':0})
Beispiel #26
0
def reset_pwd(request):
    token=request.GET.get('token')
    print(token)
    try:
        ser = serializer(settings.SECRET_KEY, expires_in=180)
        user_id = ser.loads(token).get("id")
        print(user_id)
        if Users.objects.filter(pk=user_id):
            request.session['user_id'] = user_id
            return render(request, 'userapp/reset_pwd.html')
        return HttpResponse('token无效!')
    except:
        return HttpResponse('不好意思,链接已经失效!')
Beispiel #27
0
    def get(self, request, token):
        try:
            s = serializer(settings.SECRET_KEY, 300)
            info = s.loads(token)
            user_id = info['user_id']
            user = User.objects.get(id=user_id)
            user.is_active = True
            user.save()

            return redirect(reverse('user:login'))
        except SignatureExpired as e:
            return HttpResponse('激活已过期')
        except Exception as e:
            return render(request, '404.html')
Beispiel #28
0
 def confirm(self, token):
     s = serializer(current_app.config['SECRET_KEY'])
     # 通过loads()获得原始数据时,如果时间过期或者token被人篡改会抛出异常
     try:
         data = s.loads(token)
     except:
         return False
     # 最后对id进行验证
     if data.get('confirm') != self.id:
         return False
     self.confirmed = True
     print("111111111111111111")
     db.session.add(self)
     db.session.commit()
     return True
Beispiel #29
0
def check_verify_email_token(token):
    s = serializer(settings.SECRET_KEY,
                   expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = s.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return None
        else:
            return user
Beispiel #30
0
 def change_email(self, token):
     s = serializer(current_app.config["SECRET_KEY"])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get('change_email') != self.id:
         return False
     new_email = data.get('new_email')
     if new_email is None:
         return False
     if self.query.filter_by(email=new_email).first() is not None:
         return False
     self.email = new_email
     db.session.add(self)
     return True