Exemple #1
0
    def add_user(self, validated_data):
        result = dict()
        print(validated_data)
        # 新增用户
        try:
            new_user = User(
                user_guid=validated_data['user_guid'],
                user_name=validated_data['user_name'],
                real_name=validated_data['real_name'],
                mobile=validated_data['mobile'],
                balance=validated_data['balance'],
                available_balance=validated_data['available_balance'])
            new_user.save()

        except Exception as ex:
            print('--------------------')
            print(ex)
            print('--------------------')
            result["error_code"] = ErrorCode.用户不存在.value
            result["error"] = ''
            return result

        result["error_code"] = ErrorCode.正确.value
        result["error"] = ""
        return result
Exemple #2
0
    def post(self, request, *args, **kwargs):
        email_address = request.data["email"]
        username = email_address.split("@")
        code = code_generator()

        try:
            new_user = User(email=email_address,
                            username=username[0],
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=code)
            registration_profile.save()
        except IntegrityError:
            return Response(
                f"The email address '{email_address}' is already taken.")

        send_mail(
            'Fresh Garden Registration Code',
            f"Here is your registration code {registration_profile.code}",
            '*****@*****.**',
            [new_user.email],
            fail_silently=False,
        )
        serializer = self.get_serializer(new_user)
        return Response(serializer.data)
Exemple #3
0
    def post(self, request, *args, **kwargs):
        email_data = self.request.data
        email_address = email_data.__getitem__("email")
        length = 5
        numbers = '0123456789'
        validation_code = ''.join(
            random.choice(numbers) for _ in range(length))
        subject = 'Welcome to Luna'
        message = 'Here is your validation code ' + validation_code
        recipient = email_address
        send_mail(subject,
                  message,
                  EMAIL_HOST_USER, [recipient],
                  fail_silently=False)

        try:
            new_user = User(email=email_address,
                            username=email_address,
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=validation_code)
            registration_profile.save()
            return Response(status=status.HTTP_200_OK)
        except IntegrityError:
            return Response(data="This email is already taken.", status=400)
Exemple #4
0
def register(req):

    if req.method == "GET":
        return render(req, 'register.html')
    elif req.method == 'POST':
        username = req.POST.get('username')
        password = req.POST.get('password')
        confirm_password = req.POST.get('confirm_password')
        email = req.POST.get('email')
        phone = req.POST.get('phone')
        if password and username and email and password == confirm_password:
            users = User.objects.filter(username=username)
            if users:
                return render(req, 'register.html', {'msg': "账号存在"})
            else:
                user = User(username=username,
                            password=password,
                            email=email,
                            phone=phone)
                user.save()
                return render(req, 'register.html')
        else:
            return render(req, 'register.html', {'msg': "参数不正确"})
    else:
        return render(req, 'register.html', {'msg': "不支持该方式传送"})
Exemple #5
0
    def post(self, request, *args, **kwargs):
        email_address = request.data["email"]
        username = email_address.split("@")
        code = code_generator()

        try:
            new_user = User(email=email_address,
                            username=username[0],
                            is_active=False)
            new_user.save()
            registration_profile = RegistrationProfile(user=new_user,
                                                       code=code)
            registration_profile.save()
        except IntegrityError:
            return Response(
                f"The email address '{email_address}' is already taken.")

        # TODO uncomment for production
        # send_mail(
        #     'Motion Registration Code',
        #     f"Here is your registration code {registration_profile.code}",
        #     '*****@*****.**',
        #     [new_user.email],
        #     fail_silently=False,
        # )
        serializer = self.get_serializer(new_user)
        return Response(serializer.data)
Exemple #6
0
def register():
    resp = {'result': 'success', 'status': 200, 'msg': 'success'}
    data = json.loads(request.data)
    email = data['email'] if 'email' in data else ''
    password = data['password'] if 'password' in data else ''
    checkcode = data['checkcode'] if 'checkcode' in data else ''

    if checkcode.upper() != session['valicode'].upper():
        resp['result'] = 'failed'
        resp['msg'] = "验证码不正确"
        resp['status'] = 401
        return jsonify(resp)

    user = User.query.filter_by(email=email).first()
    if user:
        resp['result'] = 'failed'
        resp['msg'] = "邮箱已注册"
        resp['status'] = 401
        return jsonify(resp)

    new_user = User()
    new_user.email = email
    new_user.password_hash = generate_password_hash(password)
    db.session.add(new_user)
    db.session.commit()

    login_user(new_user, True)

    return jsonify(resp)
Exemple #7
0
def valid_fech(value):
    from apps.user.models import User
    fec_val = datetime.strptime(str(value), "%Y-%m-%d")
    fec_may = datetime.strptime(User().my_age(), "%Y-%m-%d")
    fec_err = datetime.strptime(User().my_age(edad=False), "%Y-%m-%d")

    if fec_val > fec_may:
        raise ValidationError(_('18+'))

    if fec_val < fec_err:
        raise ValidationError(_('99+'))
Exemple #8
0
 def init(self):
     """
     初始化服务准备工作
     :return:
     """
     # self.create_default_media_dir()
     from apps.post.models import Category
     from apps.other.models import FeedbackCategory
     from apps.user.models import User
     User.create_default_super_user()
     Category.create_default_category()
     FeedbackCategory.create_default_category()
Exemple #9
0
def store_data_user(data):
    detail = UserDetail(
        fullname=data['fullname'],
        phone_number=data['phone_number'],
    )

    user = User(username=data['username'],
                email=data['email'],
                password=data['password'],
                user_detail=detail)
    # try:
    user.commit()
    return user
Exemple #10
0
 def post(self, request):
     form = RegisterForm(request.POST)
     if form.is_valid():
         username = form.cleaned_data.get('username', '')
         email = form.cleaned_data.get('email', '')
         password = form.cleaned_data.get('password', '')
         users = User()
         users.username = username
         users.password = make_password(password)
         users.email = email
         users.is_active = False
         users.save()
         token = token_confirm.generate_validate_token(username)
         # message = "\n".join([u'{0},欢迎加入我的博客'.format(username), u'请访问该链接,完成用户验证,该链接1个小时内有效',
         #                      '/'.join([settings.DOMAIN, 'activate', token])])
         #send_mail(u'注册用户验证信息', message, settings.EMAIL_HOST_USER, [email], fail_silently=False)
         send_register_email.delay(email=email,
                                   username=username,
                                   token=token,
                                   send_type="register")
         return JsonResponse({
             'valid': True,
             'status': 200,
             'message': u"请登录到注册邮箱中验证用户,有效期为1个小时"
         })
     return JsonResponse({
         'status': 400,
         'data': form.errors,
         'valid': False
     })
Exemple #11
0
def init_database():
    app.db.create_all()

    user1 = User("bob3", "bob", "dylan", "emprendedor", "123")
    user2 = User("bob4", "bob", "esponja", "cocinero", "123")

    app.db.session.add(user1)
    app.db.session.add(user2)

    app.db.session.commit()

    yield app.db

    app.db.drop_all()
Exemple #12
0
def register(request):
    r = json.loads(request.body)
    account = r['account']
    password = r['password']
    code = r['code']
    if judge_type(account) is None:
        return JsonResponse({'success': False, 'msg': "账号格式有误!"})
    # 从redis缓存中读取缓存信息 account唯一
    check_code = cache.get(account)
    print(check_code)
    # 验证验证码是否正确
    if check_code == code:
        # 新加用户
        user = User()
        user.username = '******' + shuffle_str(True)[0:6]
        # 判断账号类型
        if judge_type(account) == 'phone':
            user.phone = account
        else:
            user.email = account
        # 密码加密
        user.password = encrypt(password)
        print(user.password)
        # 保存
        user.save()
        return JsonResponse({'success': True, 'msg': "注册成功!"})
    else:
        return JsonResponse({'success': False, 'msg': "验证码错误!"})
Exemple #13
0
def init_database():
    app.db.create_all()

    user1 = User("bob3", "bob", "dylan", "Scrum Team", "123")
    user2 = User("bob4", "bob", "esponja", "Product Owner", "123")
    user2 = User("bob5", "bob", "esponja", "Product Owner", "123")

    app.db.session.add(user1)
    app.db.session.add(user2)

    app.db.session.commit()

    yield app.db

    app.db.drop_all()
Exemple #14
0
def add(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        try:
            user = User.objects.get(id=int(request.session.get('my_user_id', 0)))
        except User.DoesNotExist:
            user = User()
        user.name = name
        user.save()
        request.session['my_user_id'] = user.id
        if request.is_ajax():
            return JsonResponse({'user': user.id})
        else:
            return redirect('/ginny/%s/' % user.id)
    raise Http404
Exemple #15
0
 def post(self):
     try:
         args = request.get_json()
         name = args.get('data').get('name')
         password = args.get('data').get('password')
         repassword = args.get('data').get('repassword')
         phone = args.get('data').get('phone')
         email = args.get('data').get('email')
         get_phone = User.query.filter(User.phone == phone).first()
         ret = re.match('1[3-9]\d{9}', phone)
         if ret:
             if password == repassword:
                 if not get_phone:
                     user = User(username=name,
                                 password=password,
                                 phone=ret.group(),
                                 email=email)
                     db.session.add(user)
                     db.session.commit()
                 else:
                     return jsonify({'msg': '手机号码已存在!'})
             else:
                 return jsonify({'msg': '两次密码输入不一致!'})
         else:
             return jsonify({'code': 400, 'msg': '请输入合法的手机号码!'})
     except Exception as e:
         return jsonify({'code': 404, 'msg': '操作失败!'})
     return jsonify({'code': 200, 'msg': '操作成功!'})
Exemple #16
0
 def post(self, req, **kwargs):
     data = UserSerializer(data=req.data)
     if data.is_valid():
         User(**data.data).save()
         return HttpResponseRedirect('/user/signup/')
     else:
         return Response({'res':'Не пройдена валидация'})
Exemple #17
0
    def identify(self, request):
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return return_fail_http_json_result('', 'No token information')

        auth_token_info = auth_header.split(" ")
        if (not auth_token_info or auth_token_info[0] != 'JWT'
                or len(auth_token_info) != 2):
            return return_fail_http_json_result(
                '', 'Authorization information incorrect')

        auth_token = auth_token_info[1]
        result, payload = self.decode_auth_token(auth_token)
        if not result:
            return return_fail_http_json_result('', payload)

        user = User.get(User, payload['data']['id'])
        if not user:
            return return_fail_http_json_result('', 'User not found')

        if (user.login_time != payload['data']['login_time']):
            return return_fail_http_json_result(
                '', 'Token has changed, Please login again')

        return return_success_http_json_result(user.id, 'Request success')
Exemple #18
0
def register(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        truename = request.POST['truename']
        department = request.POST['department']
        phone = request.POST['phone']
        user = User(username=username,
                    password=password,
                    truename=truename,
                    department=department,
                    phone=phone)
        user.save()
        return HttpResponse(json.dumps(dict(succeed=True)))
Exemple #19
0
def add_user():
    if request.method == 'GET':
        return render_template('add_user.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        phone = request.form.get('phone')
        province = request.form.get('province')
        city = request.form.get('city')
        detail = request.form.get('detail')
        is_continue = request.form.get('continue')
        if username:
            user_ = User(username=username)
            db.session.add(user_)
            if None not in (phone, province, city, detail):
                db.session.add(
                    Address(uid=user_.uid,
                            phone=phone,
                            province=province,
                            city=city,
                            detail=detail))
                if is_continue:
                    return render_template('add_user.html')
                else:
                    return redirect(url_for('.index', page=1, size=3))
            else:
                return render_template('add_user.html', msg='所有选线为必填项,请补全!')
        else:
            return render_template('add_user.html', msg='昵称不能为空!')
Exemple #20
0
    def get_user(self):
        if self.db_user:
            return self.db_user
        
        # Try to fetch a User via cookie
        self.db_user = User.get( read_user_cookie( self ) )

        return self.db_user
Exemple #21
0
def bindingQQ(request):
    """
    QQ 注册账号
    :param request:
    :return:
    """
    if request.method == 'POST':
        openid = request.POST.get('openid')
        figureurl_qq_1 = request.POST.get('figureurl_qq_1')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        email = request.POST.get('email')
        if password != password1:
            return render(
                request, 'pc/qqregister.html', {
                    'openid': openid,
                    'figureurl_qq_1': figureurl_qq_1,
                    'nickname': nickname,
                    'error': '两次密码不一致'
                })
        else:
            User.objects.filter(email=email).exists()
            if User.objects.filter(email=email).exists():
                return render(
                    request, 'pc/qqregister.html', {
                        'openid': openid,
                        'figureurl_qq_1': figureurl_qq_1,
                        'nickname': nickname,
                        'error': '邮箱已存在'
                    })
            else:
                user = User()
                user.username = nickname
                user.email = email
                user.user_image = figureurl_qq_1
                user.password = make_password(password1)
                user.save()
                qq = OAuthQQ()
                user_id = get_object_or_404(User, email=email).id
                qq.user_id = user_id
                msg = UserMessage()
                msg.user_id = user_id
                msg.to_user = User.objects.get(username='******')
                msg.message = '欢迎加入本站,在使用过程中有什么疑问,请联系管理员'
                msg.has_read = False
                msg.is_supper = True
                msg.save()
                qq.qq_openid = openid
                qq.nickname = nickname
                qq.figureurl_qq = figureurl_qq_1
                qq.save()
                user = authenticate(request, username=email, password=password)
                login(request, user)
                return HttpResponseRedirect(reverse('home'))
Exemple #22
0
    def get( self ):
        users = User.all()
        for u in users:
            u.put()

        return
        
        # Don't run this again!
        names = [ 'Yuriy Blokhin', 'Mike Roberts', 'Andrei Skarine', 'Chris Best', 'Chris Fairles', 'Daniel Hendry', 'Jonathan Meyer', 'Nick Belyaev',
        'Adam Allidina', 'Peter Heinke', 'Julian Haldenby', 'Michael MacKenzie', 'Angela Watkins', 'Peter Wagner', 'Vick Yao', 'Erika Podlovics', 'Christine Thayer', 'Heather Galt',
        'Adrian Kenny', 'Jairaj Sethi', 'Benjamin Chilibeck', 'Rob McLeod', 'Ted Livingston', 'Barbara Macdonald']
        
        urls = ['static/imgs/YuriyBlokhin.jpeg', 'static/imgs/MichaelRoberts.jpg', 'static/imgs/AndreiSkarine.jpg', 'static/imgs/ChrisBest.jpg',
        'static/imgs/ChrisFairles.jpg', 'static/imgs/DanielHendry.jpg', 'static/imgs/JonathanMeyer.jpg', 'static/imgs/NikolayBelyaev.jpg', 'static/imgs/AdamAllidina.jpg',
        'static/imgs/PeterHeinke.jpg', 'static/imgs/JulianHaldenby.jpg', 'static/imgs/MichaelMacKenzie.jpg', 'static/imgs/AngelaWatkins.jpg', 'static/imgs/PeterWagner.jpg', 'static/imgs/VickYao.jpg', 'static/imgs/ErikaPodlovics.jpg', 'static/imgs/ChristineThayer.jpg', 'static/imgs/HeatherGalt.jpg', 'static/imgs/AdrianKenny.jpeg', 'static/imgs/JairajSethi.jpeg', 'static/imgs/BenjaminChilibeck.jpg', 'static/imgs/RobMcLeod.jpg', 'static/imgs/TedLivingston.jpg', 'static/imgs/BarbaraMacdonald.jpg']
        
        for i in range( 0, 25 ):
            user = User.create( names[i], urls[i] )
Exemple #23
0
 def post(self):
     args = self.parser.parse_args()
     username = args.get(arg_username,'')
     password = args.get(arg_password,'')
     if username and password:
         try:
             user = User()
             user.username = username
             user.passwd = password
             db.session.add(user)
             db.session.commit()
             data = {'user': user}
             result = {
                 'data': data
             }
             return result
         except:
             db.session.rollback()
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        if password == repassword:
            # 注册用户
            user = User()
            user.username = username
            user.password = hashlib.sha256(
                password.encode('utf-8')).hexdigest()
            user.phone = phone
            # 添加并提交
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('user.user_center'))
    return render_template('user/register.html')
def init_database():
    app.db.create_all()

    user1 = User("bob3", "bob", "dylan", "Scrum Team", "123")
    user2 = User("bob4", "bob", "esponja", "Product Owner", "123")

    project1 = Project("description1", 1, ProjectStatus.active)
    project2 = Project("description2", 1, ProjectStatus.active)

    app.db.session.add(user1)
    app.db.session.add(user2)
    app.db.session.add(project1)
    app.db.session.add(project2)

    app.db.session.commit()

    yield app.db

    app.db.drop_all()
def authentication(token: str) -> Union[User, object]:
    url = f'{settings.AUTH_HOST}/api/v1.0/system/users/decode-token'
    try:
        resp = requests.get(url=url, headers={'Authorization': token}, timeout=settings.REQUEST_TIMEOUT)
        if resp.status_code == 200:
            data = resp.json()
            return User(**data['data'])
        return
    except (requests.ReadTimeout, requests.Timeout) as err:
        logger.error(f'error response from auth. {err}')
        return
Exemple #27
0
 def get(self):
     result = Auth.identify(Auth, request)
     if (result['status'] and result['data']):
         user = User.get(User, result['data'])
         returnUser = {
             'id': user.id,
             'name': user.username,
             'email': user.email
         }
         result = return_success_http_json_result(returnUser, "Request success")
     return jsonify(result)
Exemple #28
0
def register(request, useremail: str, username: str, password: str):
    email = useremail
    user = User.objects.get(email=email)
    if user is not None:
        return HttpResponse(json.dumps({"status": 201, "msg": "邮箱已被注册"}))
    user = User.objects.get(username=username)
    if user is not None:
        return HttpResponse(json.dumps({"status": 202, "msg": "用户名已存在"}))
    user = User(username=username, email=useremail, password=password)
    user.save()
    return HttpResponse(json.dumps({"status": 200, "msg": "注册成功"}))
Exemple #29
0
def init_db(app):
    # 生成数据库表
    db.create_all()
    app.logger.debug('创建表')
    if Role.query.first():
        return
    role_admin = Role(role_name="管理员", role_desc="系统管理员")
    role_audit = Role(role_name="审计员", role_desc="审计员")
    role_ordinary = Role(role_name="普通用户", role_desc="普通管理员")
    db.session.add_all([role_admin, role_audit, role_ordinary])
    db.session.commit()
    app.logger.debug('初始化角色成功')
    admin = User(user_name="admin",
                 role_id=1,
                 create_time=TimeManager.now(),
                 status=1,
                 last_passwd_change_time=TimeManager.now())
    admin.pwd = 'admin'
    db.session.add(admin)
    db.session.commit()
    app.logger.debug('初始化用户成功')
Exemple #30
0
def register2():
    if request.method == 'POST':
        email = request.form.get('email')
        username = request.form.get('username')
        password = request.form.get('password')
        re_password = request.form.get('password2')
        if password == re_password and len(password) >= 8:
            i = 6
            b = []
            while i >= 1:
                a = random.randint(0, 9)
                i -= 1

                b.append(str(a))
            print(b)
            ve_num = ''.join(b)
            en_num = generate_password_hash(ve_num)
            senmail('verify', '*****@*****.**', 'verify', ve_num)
            ip = input('verify:')
            if check_password_hash(en_num, ip):
                user = User()
                user.email = email
                user.username = username
                # user.password = hashlib.sha256(password.encode('utf-8')).hexdigest()  # encrypted
                # 需要加密密碼
                user.set_password(password)
                db.session.add(user)
                db.session.commit()
                return 'content'
            else:
                print('code is wrong')
        else:
            pass
            return 'fail'
Exemple #31
0
    def signup_user(self, validated_data):
        oid = validated_data['oid']
        oid = oid.lower()
        username = validated_data['username']
        access_token = validated_data['access_token']
        try:
            phone = get_phone(access_token)
        except Exception as e:
            raise ValidationError(detail='Invalid phone token!')

        if check_oid_exists(oid):
            raise PermissionDenied(detail='Organization exists!')
        if check_username_exists(oid=oid, username=username):
            raise PermissionDenied(detail='Username exists!')

        org = Organization.objects.create(oid=oid)
        usage = Usage(org=org, exp_date=trial_cycle())
        usage.save()
        subscription = Subscription(org=org,
                                    current_usage=usage,
                                    _is_trial=True)
        subscription.save()

        user = User(
            username=create_username(oid=oid, username=username),
            phone=phone,
            is_active=True,
            role=ROLE_DICT['Organizer'],
            org=org,
        )
        user.set_unusable_password()
        user.save()
        userstate = UserState.objects.create(user=user)
        jwt_token = jwt_encode_handler(jwt_payload_handler(user))
        return user, jwt_token
Exemple #32
0
def register(req):
    """
    注册
    """
    print("############")
    is_verified = req.session.get("verified")
    if req.method == 'POST' and is_verified:
        urf = UserRegisterForm(req.POST)
        if urf.is_valid():
            try:
                user = User(
                    username=urf.cleaned_data['username'],
                    first_name=urf.cleaned_data['first_name'],
                    last_name=urf.cleaned_data['last_name'],
                    email=urf.cleaned_data['email'],
                    phone=urf.cleaned_data['phone'],
                    mac=urf.cleaned_data['mac'],
                    is_teacher=urf.cleaned_data['is_teacher'],
                )
                user.set_password(urf.cleaned_data['password'])
                user.save()
                return HttpResponse("User {0} Register success".format(
                    user.username))
            except IntegrityError as e:
                return HttpResponse("IntegrityError error: {0}".format(e))
        else:
            # TODO
            return HttpResponse(str(urf.cleaned_data))
    return HttpResponse(status=403)
Exemple #33
0
def register():
    if request.method == 'POST':
        username = request.form.get('username')  # request是从页面获取的,表单一点提交就会提交信息
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        if password == repassword:  # 如果密码一致
            # 1注册用户,与模型结合
            user = User()
            # 2给对象的属性赋值
            user.username = username  # .username表示访问user的属性,获取属性
            user.password = generate_password_hash(
                password)  # 使用自带的函数实现加密generate_password_hash
            user.phone = phone  # 属性赋值
            # 添加并提交
            # 3.将user对象添加到session中(类似缓存)
            db.session.add(user)
            # 4.提交到数据库
            db.session.commit()
            return render_template('base.html')

    return render_template('user/register.html')
    def test_password_hashing(self):
        user = User(
            email='*****@*****.**',
            password='******',
        )
        user.save()

        # Check that password is converted to a hash upon saving
        self.assertTrue(check('password', user.password))

        # Check that password is not hashed again when its value did not change
        user.save()
        self.assertTrue(check('password', user.password))

        # Check that password is hashed again when its value changed
        user.password = '******'
        user.save()
        self.assertFalse(check('password', user.password))
        self.assertTrue(check('$this_is_my_new_password', user.password))
Exemple #35
0
    def post( self ):
        user = self.get_user()

        if not user:
            first_name  = self.request.get( 'firstName' )
            last_name   = self.request.get( 'lastName' )
            email       = self.request.get( 'email' )
            
            user        = User.create( first_name, last_name, email )

            # Cache the User
            self.db_user = user

            # Have to do this here to avoid a circular reference
            set_user_cookie( self, user.uuid )
        
        self.response.headers['Content-Type'] = "application/json"
        self.response.out.write( json.dumps( { 'uuid' : user.uuid,
                                               'img'  : user.img } ) )
Exemple #36
0
def registration(request):
    if request.POST:
        # filled form
        form = UserRegistrationForm(data=request.POST)
        if form.is_valid():
            # check user nick name duplicates
            nick = form.cleaned_data.get("nick")
            if User.get_by_key_name(nick):
                form._errors["nick"] = form.error_class(["User with given nick name already registered"])
            else:
                user = form.save()
                request.session["user"] = user
                # when the user login, that we rotate the session ID (security)
                request.session.regenerate_id()
                return request.redirect("go back")
    else:
        # empty form
        form = UserRegistrationForm()
    return request.render('user/registration', form = form)
Exemple #37
0
def login(request):
    if request.POST:
        # filled form
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            nick = form.cleaned_data.get("nick")
            password = form.cleaned_data.get("password")
            user = User.get_by_key_name(nick)
            # correct user
            if user and user.password == password:
                request.session["user"] = user
                # when the user login, that we rotate the session ID (security)
                request.session.regenerate_id()
                return request.redirect("go back")
            else:
                form._errors["nick"] = form.error_class(["User with given nick name and password not found"])
    else:
        # empty form
        form = UserLoginForm()
    return request.render('user/login', form = form)
    def test_email_case_insensivity(self):
        u1 = User(
            email='*****@*****.**',
            password='******',
        )
        u1.save()

        with self.assertRaises(ValidationError) as context:
            u2 = User(
                email='*****@*****.**',
                password='******',
            )
            u2.full_clean()

        self.assertEqual(str(context.exception.message_dict['__all__'][0]),
                         'Email not unique')
Exemple #39
0
    def post( self ):
        menu   = self.request.get('menu').strip()
        type   = self.request.get('type').upper()
        rating = self.request.get('rating')

        if menu is not "":
            # Update the current meal to become an old meal
            current_meal = Meal.get_current()
            if current_meal:
                current_meal.status = 'past_meal'
                current_meal.rating = int( rating )
                current_meal.put()

            # Create the new meal
            new_meal = Meal.create( type, menu )

            # Tell people the meal is here!!!
            users = User.all().filter( 'notification =', True ).filter( 'email !=', '' )
            for u in users:
                taskqueue.add( queue_name = 'notificationEmail', 
                               url        = url( 'NotifyUsers' ),
                               params     = {'first_name' : u.first_name,
                                             'email'      : u.email,
                                             'menu'       : menu } )
Exemple #40
0
def getUserNamebyId(id):
    if id:
        return User.get(id)
    return '没人'
Exemple #41
0
def users_list(request):
    return request.render('user/users_list', users = User.all().order("-created"))
Exemple #42
0
    def post( self ):
        # Given a User uuid, create a Checkin obj. 
        user = User.get( self.request.get('user_uuid') )
        meal = Meal.get_current()

        Checkin.create( meal, user )
Exemple #43
0
def load_user(id):
    return User.get(id)