コード例 #1
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #2
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         return 'User created!', 201
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         error = Errors("Given e-mail already in use", "email")
         return error.notunique()
     except Exception as e:
         raise InternalServerError
コード例 #3
0
ファイル: auth.py プロジェクト: hnagri52/CourseHub
 def post(self):
     try:
         body = request.get_json(force=True)
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {"id": str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         print(e.message, e.args)
コード例 #4
0
 def post(self):
     try:
         body = request.get_json()
         user =  User(**body)
         user.save()          
         return 'User Registered sucessfully', 200         
     except FieldDoesNotExist:
         raise SchemaValidationError
     except ValidationError:
         raise SchemaValidationError        
     except NotUniqueError:
         raise UserNameAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #5
0
ファイル: views.py プロジェクト: pusisi1/project
def signup(request):
    # 실제 데이터베이스에 데이터를 저장(회원가입)
    if request.method == 'POST':
        # 회원정보 저장
        email = request.POST.get('email')
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        user = User(email=email, name=name, pwd=pwd)
        user.save()
        return HttpResponseRedirect('/main/')


# 화원가입을 위한 양식 전송

    return render(request, 'signup.html')
コード例 #6
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         #admin = Admin.objects.get(id=admin.id).to_json()
         #return Response(admin, mimetype="application/json", status=200)
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #7
0
ファイル: auth.py プロジェクト: mianfg/pictomaker-api
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         response = {'id': user.id}
         return Response(json.dumps(response),
                         mimetype="application/json",
                         status=200)
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #8
0
 def post(self):
     try:
         parser = reqparse.RequestParser()
         parser.add_argument("email", type=str)
         parser.add_argument("password", type=str)
         parser.add_argument("name", type=str)
         parser.add_argument("dob", type=str)
         parser.add_argument("mobile", type=str)
         q = parser.parse_args()
         if q.email is None or q.password is None or q.name is None or q.dob is None or q.mobile is None:
             return {
                 "success": False,
                 "message": "Email, password, name, mobile or date of birth is missing"
             }
         else:
             user_count = User.objects(email=q.email).count()
             if user_count > 0:
                 return {
                     "success": False,
                     "message": "User already exists"
                 }
             else:
                 password = generate_hash(q.password)
                 try:
                     dob = datetime.datetime.strptime(q.dob, '%d/%m/%Y')
                 except:
                     return {"success": False, "message": "Invalid date of birth. Please keep the format of dd/mm/yyyy"}
                 user = User(email=q.email, password=password, name=q.name, dob=dob, mobile=q.mobile)
                 user.save()
                 return {
                     "success": True,
                     "token": create_jwt({"email": user.email, "type": "user"}),
                     "user": user.format()
                 }
     except ValidationError as e:
         errors = list(e.to_dict())
         message = "Invalid " + ", ".join(errors)
         return {
             "success": False,
             "message": message
         }
     except Exception as e:
         print(e)
         return {
             "success": False,
             "message": "Something went wrong"
         }
コード例 #9
0
ファイル: auth.py プロジェクト: JMaylor/walkies-backend
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         expires = datetime.timedelta(days=7)
         access_token = create_access_token(identity=str(id),
                                            expires_delta=expires)
         return {'id': str(id), 'token': access_token}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #10
0
ファイル: commands.py プロジェクト: cnr-ibba/SMARTER-backend
def create_user(name):
    """ Creates a user """

    pass1 = getpass.getpass("Please enter a password: "******"Please confirm your password: "******"Password doesn't match")

    # generate password hash
    password = generate_password_hash(pass1).decode('utf8')

    # prepare to insert
    user = User(username=name, password=password)
    user.save()

    print(f"User '{name}' added ({user.id})")
コード例 #11
0
ファイル: auth.py プロジェクト: hongphi/coding-challenge
 def post(self):
     body = MultiDict(request.get_json())
     form = RegisterForm(body)
     if User.objects.filter(email=body.get("email")).count() > 0:
         return {'email': ["This email already exists"]}, 400
     if form.validate():
         user = User(**body)
         user.hash_password()
         user.save()
         expires = datetime.timedelta(minutes=20)
         access_token = create_access_token(identity=str(user.id),
                                            expires_delta=expires)
         return {
             "user": json.loads(user.to_json()),
             "access_token": access_token
         }, 200
     else:
         return form.errors, 400
コード例 #12
0
ファイル: views.py プロジェクト: weiliansong/MovieDB
def register(request):
    q_username = request.POST['username']
    q_password = request.POST['password']
    q_confirm = request.POST['password-confirm']

    if q_password != q_confirm:
        return render(request, 'login/index.html', {
            'register_message': 'Password confirm failed',
        })

    q_fname = request.POST['fname']
    q_mname = request.POST['mname']
    q_lname = request.POST['lname']
    q_dob = request.POST['dob']
    q_gender = request.POST['gender']
    q_manager = request.POST['password-manager'] == manager_password

    user = User.objects.all().filter(username=q_username)

    if user:
        return render(request, 'login/index.html', {
            'register_message': 'Existing user',
        })

    new_user = User(first_name=q_fname,
                    middle_name=q_mname,
                    last_name=q_lname,
                    username=q_username,
                    dob=q_dob,
                    gender=q_gender,
                    is_admin=q_manager,
                    password=q_password)
    new_user.save()

    if q_manager:
        return render(request, 'login/index.html', {
            'register_message': 'Registered manager user',
        })
    else:
        return render(request, 'login/index.html', {
            'register_message': 'Registered regular user',
        })
コード例 #13
0
    def post(self): 
        body = json.loads(request.data)
        
        name = body.get("username", None)
        email = body.get("email", None)
        password = body.get("password", None)
        address = body.get("address", None)
        phone_number = body.get("phone_number", None)
        gender = body.get("gender", None)

        user_found = User.objects(username__in=[name]).first()
        email_found = User.objects(email__in=[email]).first()

        if user_found:
            return Response("There already is a user by that name", mimetype="application/json", status=400)
        if email_found:
            return Response("This email already exists in database", mimetype="application/json", status=400)
        else:
            user_input = User(username = name, email= email, password = generate_password_hash(password), address = address, phone_number = phone_number, gender = gender)            
            user_input.save()
            return Response("User created", mimetype="application/json", status=201)
コード例 #14
0
    def post(self):
        body = request.get_json()
        if body is not None:
            try:
                user = User(**body)
                user.validate()
                user.hash_password()
                user.save()
            except NotUniqueError as nue:
                return {"message": "Email alreay Exists"}, 419
            except ValidationError as ve:
                return {"message": str(ve.errors)}, 420
            except FieldDoesNotExist as fdne:
                return {"message": fdne.args[0]}, 418
            except Exception as e:
                return {"message": "something went wrong"}, 400

            return {"message": "Signup Successful"}, 200
        else:
            return {
                "message": "body should be non empty, valid json object"
            }, 422
コード例 #15
0
ファイル: users.py プロジェクト: phong1233/SOEN341-Instagram
    def post(self):
        body = request.get_json()
        fields = ['username', 'password']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(body):
            return {'error': 'A field is empty or None'}, 400
        
        username = body.get('username').strip(' ')
        user = User.objects(username=username).first()
        if user is None:
            new_user = {
                'username': username,
                'password': body.get('password'),
                'nb_followers': 0,
                'nb_following': 0,
                'nb_login': 1,
                'nb_pictures': 0,
                'bio': 'Welcome to mypanda space!!',
                'dates': [str(datetime.now())+ ' longitude: ' + str(body.get('longitude'))+ ' latitude: ' + str(body.get('latitude'))],

            }
            new_user = User(**new_user)
            new_user.hash_password()
            new_user.save()
            expires = timedelta(hours=3)
            access_token = create_access_token(identity=str(new_user.id), expires_delta=expires)
            return {'token': access_token,
                    'bio': new_user.bio}, 200
        authorized = user.check_password(body.get('password'))
        if not authorized:
            return {'error': 'Password does not match username'}, 401
        if authorized:
            user.update(nb_login=user.nb_login + 1)
            user.update(push__dates=str(datetime.now())+' longitude: '+str(body.get('longitude'))+' latitude: '+str(body.get('latitude')))
            expires = timedelta(hours=3)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token,
                    'bio': user.bio}, 200
コード例 #16
0
def create_user():
    role = get_jwt_claims()['role']
    if role not in ROLE or role == 'USER':
        return jsonify({'message': 'Permission denied'}), 403

    data = request.get_json()
    username = data.get('username', None)
    password = data.get('password', None)
    role = data.get('role', None)
    if username is not None \
            and password is not None \
            and role is not None:
        try:
            if len(username) < 3:
                return jsonify(
                    {'message':
                     'username must greater than 3 characters'}), 400
            nor_username = username.strip().lower()
            if nor_username.find(' ') != -1:
                return jsonify({'message':
                                'username should not have space'}), 400
            if role not in ROLE:
                return jsonify({'message': 'invalid role'}), 400

            user = User(username=nor_username, password=password, role=role)
            user.hash_password()
            user.save()

        except NotUniqueError:
            return jsonify({"ok": False, "message": "User exist"}), 400
        return jsonify({
            'ok': True,
            'message': 'User created successfully!'
        }), 200
    else:
        return jsonify({
            'ok': False,
            'message': 'Bad request parameters!'
        }), 400
コード例 #17
0
ファイル: views.py プロジェクト: Luoyonghong/member
def reg_result(request): # 注册的结果页面
    password =  request.POST['password'] #从表单里拿到密码
    if password=='': # 没填密码
        return HttpResponse('注册失败!请填写密码')
    email =  request.POST['email']
    if email=='':# 没填邮箱
        return HttpResponse('注册失败!请填写邮箱')
    realname =  request.POST['realname']
    if realname=='':
        return HttpResponse('注册失败!请填写真实姓名')
    invitecode =  request.POST['invitecode']
    if invitecode=='':
        return HttpResponse('注册失败!请填写邀请码')
    u=User() # 新建一个User对象,把它存入数据库
    u.email=email
    u.password=hashlib.sha1(password).hexdigest() # 这是生成hash值代替明文的密码
    u.name=realname
    u.sec=Section.objects.get(id=1)
    u.save()
    request.session['user']=u # 把user对象放到session里面去
    result=get_template('result.html')
    resultHtml=result.render(Context())
    return HttpResponse(resultHtml)
コード例 #18
0
    def post(self):
        data = request.get_json()
        schema = RegisterSchema()
        try:
            validated_data = schema.load(data)
        except marshmallow.exceptions.ValidationError as error:
            message = "请求错误"
            for msg in error.messages.values():
                message = msg[0]
            resp = {"status": 0, "msg": message, "errors": error.messages}
            return resp, 200

        user = User(**validated_data)
        user.hash_password()
        user.save()
        id = user.id
        return {
            "status": 1,
            "msg": "ok",
            "data": {
                "id": str(id)
            },
        }, 200
コード例 #19
0
ファイル: testAuth.py プロジェクト: nerostamas/python-flask
    def test_cannotLoginWithBlankPasswordOrBlankUsername(self):
        user = User(username="******",
                    password="******",
                    role="SUPPORTER")
        user.hash_password()
        user.save()

        response = self.app.post('/api/auth/login',
                                 data=json.dumps(
                                     dict(username='', password='******')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(401, response.status_code)
        self.assertIn('Username can not be blank',
                      response.json.get('message', None))

        response = self.app.post('/api/auth/login',
                                 data=json.dumps(
                                     dict(username='******', password='')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(401, response.status_code)
        self.assertIn('Password can not be blank',
                      response.json.get('message', None))
コード例 #20
0
    def post(self):
        """Create a new User object following the User model.

        Yields:
            Save a new User with the required username, email, password
            fields.
            Hash the password.
            Create three Snippets for the user to have some UI to play with
            upon authentication.
        Flags:
            Errors and returns status code with error message,
                200, otherwise.
        Returns:
            {dict}: JSON Flask Response
                with an access token and a username.
                sets a refresh cookie in headers.
        Note:
            The computation to update, save, reload a Snippet is required to
            ensure Objects have fully landed before they are referenced. It is extra 
            complicated for this endpoint as we are awaiting reloads for three models:
            User, Collection and Snippet, all of which vary in `having to exist` before
            the other.
        """
        try:
            body = request.get_json()
            user = User(**body)

            user.hash_password()
            user.save()
            user.reload()

            now = datetime.datetime.now(datetime.timezone.utc)

            id = user.id
            username = user.username

            # Required to instantiate a new reference to the very same
            # and very new User for the purposes of attaching an owner
            # to the snippets.
            saved_user = User.objects.get(username=username)

            snippet_py = Snippet(
                title="{}.py".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="python",
                value="print('hello {}')".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_js = Snippet(
                title="{}.js".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="javascript",
                value="console.log('hello {}');".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_sh = Snippet(
                title="{}.sh".format(username),
                tags=["first post"],
                description="From Cheat-Hub",
                language="bash",
                value="#!/bin/bash\n\necho 'hello {}'".format(username),
                addedBy=saved_user,
                addedOn=now,
            )

            snippet_py.save()
            snippet_py.reload()
            snippet_js.save()
            snippet_js.reload()
            snippet_sh.save()
            snippet_sh.reload()

            user.update(push_all__snippets_created=[
                snippet_py, snippet_js, snippet_sh
            ])
            user.save()
            user.reload()

            collection = Collection(
                name="Greetings {}".format(username),
                snippets=[snippet_py, snippet_js, snippet_sh],
                date=now,
                owner=user,
            )

            collection.save()

            user.update(push__collections=collection)
            user.save()

            expires = datetime.timedelta(hours=3)
            access_token = create_access_token(identity=str(username),
                                               expires_delta=expires)
            refresh_token = create_refresh_token(identity=str(id),
                                                 expires_delta=expires)
            refresh_cookie = [("Set-Cookie",
                               "refresh_token={}".format(refresh_token))]

            return (
                {
                    "access_token": access_token,
                    "username": username,
                },
                200,
                refresh_cookie,
            )

        except FieldDoesNotExist:
            return {"message": "Request is missing required fields."}, 400

        except NotUniqueError:
            return {
                "message": "User with given email address already exists."
            }, 401

        except Exception as e:
            return {"message": "Something went wrong."}, 500
コード例 #21
0
ファイル: test.py プロジェクト: JYEEEEE/LuckyDraw
def test_save():
    user = User()
    user.login_name = 'test3'
    user.login_pass = '******'
    print(user.save())
コード例 #22
0
ファイル: index.py プロジェクト: dezagfx/Pytunes-Server
def create_account():

    error_message = []

    name = request.forms.get('name', '')
    password = request.forms.get('password', '')
    password_confirmation = request.forms.get('password_confirmation', '')
    email = request.forms.get('email', '')

    # Validaçao:
    if name == '':
        error_message.append('O nome de Utilizador esta vazio')
    if password == '':
        error_message.append('O campo password esta vazio')
    if password is not None and len(password) > 6:
        error_message.append('A password tem de ter pelo menos 6 caracteres')
    if password_confirmation == '':
        error_message.append('O campo confirmaçao de password esta vazio')
    if password != password_confirmation:
        error_message.append('As passwords nao sao iguais')

    # http://stackoverflow.com/questions/8022530/
    # python-check-for-valid-email-address/8022584#8022584
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        error_message.append('O endereço de email nao e valido')

    # Ja existe algum utilizador na base de dados com este nome?
    if name != '':
        u = User.get_by_name(name)
        if u is not None:
            error_message.append('O nome de utilizador ja existe')
    # Ja existe algum utilizador na base de dados com este Email?
    if email != '':
        u = User.get_by_email(email)
        if u is not None:
            error_message.append('O email ja existe')

    # Alguma das Validaç~oes devolveu erro?
    if len(error_message) > 0:
        return jresp.reply(
                payload=None,
                success=False,
                error_message=error_message
            )
    else:
        # 1->Inserir o novo utilizador
        # 2->Enviar o email
        plaintext_password = password
        hashed_password = auth.hash_password(plaintext_password)

        try:
            user = User(name=name, email=email, password=hashed_password)
            user.save()
        except:
            error_message.append('Erro ao comunicar com a base de dados!')
            return jresp.reply(
                    response=response,
                    payload=None,
                    success=False,
                    error_message=error_message,
                    status=500
                )
        '''
        from services import mailgun as mail
        try:
            mail.send(template='account_confirmation', name=name, email=email)
        except:
            error_message.append('Erro ao enviar email!')
            return jresp.reply(
                    response=response,
                    payload=None,
                    success=False,
                    error_message=error_message
                )
        '''
        # Tudo correu bem:
        payload = [{
                'message': 'Conta de utilizador criada com sucesso.'
                }]
        return jresp.reply(
                payload=payload,
                )
コード例 #23
0
    def post(self):
        """Method to register a new user
        """
        if request.data["username"].strip(" ") and len(request.data["password"]) >= 8:
            user = User.query.filter_by(
                username=request.data["username"]).first()

            email = User.query.filter_by(
                email=request.data["email"]).first()

            email_regex = re.search(r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",
                                    request.data["email"])

            if not user and not email and email_regex:
                try:
                    username = request.data["username"]
                    email = request.data["email"]
                    password = request.data["password"]

                    user = User(username=username, email=email, password=password)
                    user.save()

                    response = {
                        "message": "Registration successful"
                    }

                    return make_response(jsonify(response)), 201
                except Exception as e:
                    response = {
                        "message": str(e)
                    }

                    return make_response(jsonify(response)), 401

            elif not user and not email_regex:
                response = {
                    "message": "Invalid email"
                }

                return make_response(jsonify(response)), 400

            elif not user and email:
                response = {
                    "message": "Email is already in use, try a new email address"
                }

                return make_response(jsonify(response)), 400

            else:
                response = {
                    "message": "User already exists"
                }

                return make_response(jsonify(response), 409)
        elif request.data["username"].strip(" ")and 0 < len(request.data["email"]) < 8:
            response = {
                "message": "Email cannot be less than 8 characters"
            }

            return make_response(jsonify(response)), 400

        else:
            response = {
                "message": "The username or password cannot be empty"
            }
            return make_response(jsonify(response)), 400
コード例 #24
0
ファイル: views.py プロジェクト: TombRaiderjf/member
def reg_result(request): # 注册的结果页面
    u=User() # 新建一个User对象,把它存入数据库
    password =  request.POST['password'] #从表单里拿到密码
    if password=='': # 没填密码
        return HttpResponse('注册失败!请填写密码')
    email =  request.POST['email']
    if email=='':# 没填邮箱
        return HttpResponse('注册失败!请填写邮箱')
    name =  request.POST['name']
    if name=='':
        return HttpResponse('注册失败!请填写真实姓名')
    invitecode =  request.POST['invitecode']
    if invitecode=='':
        return HttpResponse('注册失败!请填写邀请码')
    sec = request.POST['sec']
    if sec==u'主席团':
        u.sec=Section.objects.get(id=2)
    if sec==u'技术部':
        u.sec=Section.objects.get(id=1)
    if sec==u'运营部':
        u.sec=Section.objects.get(id=3)
    if sec==u'宣传部':
        u.sec=Section.objects.get(id=4)
    if sec==u'财务部':
        u.sec=Section.objects.get(id=5)
    
    college = request.POST['college']
    major = request.POST['major']
    entry_year = request.POST['entry_year']
    grade = request.POST['grade']
    campus = request.POST['campus']
    sex = request.POST['sex']
    phone = request.POST['phone']
    province = request.POST['province']
    city = request.POST['city']
    area = request.POST['area']
    qq = request.POST['qq']
    love = request.POST['love']
    #city = request.POST['city']

    u.school='南开大学'
    u.email=email
    u.password=hashlib.sha1(password).hexdigest() # 这是生成hash值代替明文的密码
    u.name=name
    u.college=college
    u.major=major
    u.entry_year=entry_year
    u.grade=grade
    u.campus=campus
    u.sex=sex
    u.phone=phone
    u.province=province
    u.city=city
    u.area=area
    u.qq=qq
    u.love=love
    u.effective=1
    u.authority=0

    try: # 测试邮箱是否已经被使用过了
        User.objects.get(email = email)
    except User.DoesNotExist:
        pass
    else:
        return HttpResponse("该邮箱已被注册,请您换一个未被注册过的有效邮箱进行注册!")

    try:
        c=Code.objects.get(code=invitecode)
        if c.effective==0:
            return HttpResponse("该邀请码已经被使用过了!请确认您拥有正确的邀请码!")
        else:
            u.save()
            c.effective=0
            c.use =User.objects.get(email = email)  # 把验证码和用户关联上
            c.save()
    except Code.DoesNotExist:
        return HttpResponse("该邀请码不存在!请确认您拥有正确的邀请码!")
    
    request.session['user']=u # 把user对象放到session里面去
    result=get_template('result.html')
    resultHtml=result.render(Context())
    return HttpResponse(resultHtml)
コード例 #25
0
ファイル: views.py プロジェクト: NKMSC/member
def reg_result(request):  # 注册的结果页面
    u = User()  # 新建一个User对象,把它存入数据库
    password = request.POST['password']  #从表单里拿到密码
    if password == '':  # 没填密码
        return HttpResponse('注册失败!请填写密码')
    email = request.POST['email']
    if email == '':  # 没填邮箱
        return HttpResponse('注册失败!请填写邮箱')
    name = request.POST['name']
    if name == '':
        return HttpResponse('注册失败!请填写真实姓名')
    invitecode = request.POST['invitecode']
    if invitecode == '':
        return HttpResponse('注册失败!请填写邀请码')
    sec = request.POST['sec']
    if sec == u'主席团':
        u.sec = Section.objects.get(id=2)
    if sec == u'技术部':
        u.sec = Section.objects.get(id=1)
    if sec == u'运营部':
        u.sec = Section.objects.get(id=3)
    if sec == u'宣传部':
        u.sec = Section.objects.get(id=4)
    if sec == u'顾问团':
        u.sec = Section.objects.get(id=5)

    college = request.POST['college']
    major = request.POST['major']
    entry_year = request.POST['entry_year']
    grade = request.POST['grade']
    campus = request.POST['campus']
    sex = request.POST['sex']
    phone = request.POST['phone']
    province = request.POST['province']
    city = request.POST['city']
    area = request.POST['area']
    qq = request.POST['qq']
    love = request.POST['love']
    #city = request.POST['city']

    u.school = '南开大学'
    u.email = email
    u.password = hashlib.sha1(password).hexdigest()  # 这是生成hash值代替明文的密码
    u.name = name
    u.college = college
    u.major = major
    u.entry_year = entry_year
    u.grade = grade
    u.campus = campus
    u.sex = sex
    u.phone = phone
    u.province = province
    u.city = city
    u.area = area
    u.qq = qq
    u.love = love
    u.effective = 1
    u.authority = 0

    try:  # 测试邮箱是否已经被使用过了
        User.objects.get(email=email)
    except User.DoesNotExist:
        pass
    else:
        return HttpResponse("该邮箱已被注册,请您换一个未被注册过的有效邮箱进行注册!")

    try:
        c = Code.objects.get(code=invitecode)
        if c.effective == 0:
            return HttpResponse("该邀请码已经被使用过了!请确认您拥有正确的邀请码!")
        else:
            u.save()
            c.effective = 0
            c.use = User.objects.get(email=email)  # 把验证码和用户关联上
            c.save()
    except Code.DoesNotExist:
        return HttpResponse("该邀请码不存在!请确认您拥有正确的邀请码!")

    request.session['user'] = u  # 把user对象放到session里面去
    result = get_template('result.html')
    resultHtml = result.render(
        Context(
            {
                'result':
                'You have registered successfully! <a href="/index/">click this to turnback</a>',
                'meta': 'http-equiv="refresh" content="2;url=/index/" '
            },
            autoescape=False))  #防止将'<'、 '/'和'>'自动转义
    return HttpResponse(resultHtml)
コード例 #26
0
 def post(self):
     body = request.get_json()
     user = User(**body)
     user.hash_password()
     user.save()
     return {'id': str(user.id)}, 200
コード例 #27
0
class UserTestCase(unittest.TestCase):
    def setUp(self):
        app.config.update({
            "TESTING": True,
            "TEMP_DB": True,
            "WTF_CSRF_ENABLED": False,
            "DEBUG": False
        })
        self.app = app.test_client()
        self.assertEqual(app.debug, False)
        db.disconnect()
        db.connect('sample_test')
        User.drop_collection()
        app.register_blueprint(auth_api, url_prefix='/api/auth')
        app.register_blueprint(ticket_api, url_prefix='/api/ticket')
        app.register_blueprint(comment_api, url_prefix='/api/comment')
        self.supporter = User(username="******",
                              password="******",
                              role="SUPPORTER")
        self.supporter.hash_password()
        self.supporter.save()
        self.user = User(username="******", password="******", role="USER")
        self.user.hash_password()
        self.user.save()

    def test_userCanCreateTicket(self):
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.post('/api/ticket/create',
                                 data=json.dumps(
                                     dict(title='Ticket1',
                                          content='this is my content')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual('this is my content', response.json.get('content'))

    def test_supporterCanNotCreateTicket(self):
        testUtil.test_help_login(self.app, self.supporter.username,
                                 self.supporter.username)
        response = self.app.post('/api/ticket/create',
                                 data=json.dumps(
                                     dict(title='Ticket1',
                                          content='this is my content')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(403, response.status_code)

    def test_supporterAndUserCanReplyTicket(self):
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.post('/api/ticket/create',
                                 data=json.dumps(
                                     dict(title='Ticket1',
                                          content='this is my content')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(200, response.status_code)
        ticket_id = response.json.get('_id').get('$oid')
        response = self.app.post(
            '/api/comment/' + str(ticket_id),
            data=json.dumps(dict(content='this is comment from user')),
            content_type='application/json',
            follow_redirects=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual('this is comment from user',
                         response.json.get('content'))

        # switch to supporter
        testUtil.test_help_login(self.app, self.supporter.username,
                                 self.supporter.username)
        response = self.app.post(
            '/api/comment/' + str(ticket_id),
            data=json.dumps(dict(content='this is comment from supporter')),
            content_type='application/json',
            follow_redirects=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual('this is comment from supporter',
                         response.json.get('content'))

    def test_canNotDeleteOthersComment(self):
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.post('/api/ticket/create',
                                 data=json.dumps(
                                     dict(title='Ticket1',
                                          content='this is my content')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(200, response.status_code)
        ticket_id = response.json.get('_id').get('$oid')
        response = self.app.post(
            '/api/comment/' + str(ticket_id),
            data=json.dumps(dict(content='this is comment from user')),
            content_type='application/json',
            follow_redirects=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual('this is comment from user',
                         response.json.get('content'))
        user_comment_id = response.json.get('_id').get('$oid')

        # switch to supporter
        testUtil.test_help_login(self.app, self.supporter.username,
                                 self.supporter.username)
        response = self.app.post(
            '/api/comment/' + str(ticket_id),
            data=json.dumps(dict(content='this is comment from supporter')),
            content_type='application/json',
            follow_redirects=True)
        self.assertEqual(200, response.status_code)
        sp_comment_id = response.json.get('_id').get('$oid')
        self.assertEqual('this is comment from supporter',
                         response.json.get('content'))

        # supporter can not delete user's reply
        response = self.app.delete('/api/comment/' + str(user_comment_id),
                                   content_type='application/json',
                                   follow_redirects=True)
        self.assertEqual(403, response.status_code)

        # user can not delete sp's reply
        # switch back to user
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.delete('/api/comment/' + str(sp_comment_id),
                                   content_type='application/json',
                                   follow_redirects=True)
        self.assertEqual(403, response.status_code)