Esempio n. 1
0
def register(request):
    """
    用户注册
    """
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password2'],
                email=form.cleaned_data['email'],
                )
            user.save()
            #保存用户城市数据
            users = Users(
                user=user,
                city=form.cleaned_data['citycode'],
                )
            users.save()
            
            #注册成功  
            return  render_to_response('warn.html',{'warning':'注册成功!',}, context_instance=RequestContext(request)) 
        
    else:
        form = RegistrationForm()

    return render_to_response('account/register.html',{'form':form,},
                    context_instance=RequestContext(request))
Esempio n. 2
0
def register(request):

    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        pass1 = request.POST["password1"]
        pass2 = request.POST["password2"]
        contactno = request.POST["Phno"]
        Address = request.POST["Address"]
        city = request.POST["city"]
        is_userExists = User.objects.filter(username=username).exists()
        is_emailExists = User.objects.filter(email=email).exists()
        if is_userExists and is_emailExists:
            messages.info(request, "Username amd email are already in use ")
            return redirect('register')
        elif pass1 == pass2:
            user = User.objects.create_user(username=username,
                                            email=email,
                                            password=pass1)
            data = Users(username=username,
                         email=email,
                         password=pass1,
                         address=Address,
                         city=city,
                         contactno=contactno,
                         gstn="None",
                         role='gadmin')
            data.save()
            user.save()
            return redirect('/login')
        else:
            messages.info(request, 'password not matching')
            return redirect('/register')
    return render(request, 'register.html')
 def test_user_is_not_empty(self):
     user = Users(username="******",
                  email='*****@*****.**',
                  is_active=True,
                  is_staff=False)
     user.save()
     saved_user = Users.objects.all()
     self.assertEqual(saved_user.count(), 1)
Esempio n. 4
0
    def post(self, request, *args, **kwargs):

        # idを取得
        ids = request.POST.getlist("selected")

        for user_id in ids:
            # パスワードリセットのメールを送信
            user_id = int(user_id)
            user = Users.get_valid_user_from_id(user_id)
            opts = {
                'username': user.username,
                'use_https': request.is_secure(),
                'token_generator': default_token_generator,
                'email_template_name': self.email_template_name,
                'subject_template_name': self.subject_template_name,
                'request': request,
                'html_email_template_name': None,
                'extra_email_context': None,
            }
            self.send_mail(**opts)

        result = {
            "result": 1,
        }
        return JsonResponse(result)
Esempio n. 5
0
def update_profile(usertype):
    if request and request.method == "PUT":
        try:

            auth = request.headers.get('AUTHORIZATION', b'').split()
            j = JWTTokenUtil(auth[1])
            uid = j.get_user_id()

            userObj = Users.get(uid)
            if userObj.userType != usertype:
                raise Exception("Please provide correct usertype !!!")

            body = None
            if request.data:
                body = json.loads(request.data)
                resp, err = ValidateRegistrationData(body, usertype, True)
                if err:
                    res = GetResponseObject(err, 400)
                    return res
            else:
                data = f"Empty request body !!!!"
                res = GetResponseObject(data, 400)
                log.error(err)
                return res

            user = Cognito(user_pool_id=COGNITO_USER_POOL_ID,
                           client_id=COGNITO_APP_CLIENT_ID,
                           user_pool_region=AWS_REGION)

            out, err = UpdateItem(uid, usertype, body=body, update=True)
            if err:
                raise Exception(err)

            data = "User profile updated successfully !!!"

            res = GetResponseObject(data, 200, True)
            return res

        except Exception as e:
            data = f"Error while updating user profile: {str(e)}"
            log.error(data)
            res = GetResponseObject(data)
            return res

    else:
        data = f"Invalid request method, method {request.method} not supported !!!"
        return GetResponseObject(data, 405)
Esempio n. 6
0
def user_register(request, format=None):
    """
    register an account with username and password parameters
    """

    username = request.query_params.get('username', None)
    password = request.query_params.get('password', None)

    user = Users(Username=username, Password=password)
    serializer = UserSerializer(user)
    serializer = UserSerializer(data=serializer.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    print(serializer.errors)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def test_saving_and_retrieving_user(self):
        user = Users()
        username = '******'
        email = '*****@*****.**'
        is_active = True
        is_staff = False
        user.username = username
        user.email = email
        user.is_active = is_active
        user.is_staff = is_staff
        user.save()

        saved_user = Users.objects.all()
        actual_user = saved_user[0]

        self.assertEqual(actual_user.username, username)
        self.assertEqual(actual_user.email, email)
        self.assertEqual(actual_user.is_active, is_active)
        self.assertEqual(actual_user.is_staff, is_staff)
Esempio n. 8
0
def sign_in():
    if request and request.method == "GET":
        resp, err = GetUserPasswordFromAuthHeader(request)
        if err:
            log.error(err)
            res = GetResponseObject(err, 400)
            return res

        username, password = resp[0], resp[1]

        try:
            user = Cognito(user_pool_id=COGNITO_USER_POOL_ID, \
                client_id=COGNITO_APP_CLIENT_ID, \
                user_pool_region=AWS_REGION, \
                username=username)

            user.admin_authenticate(password=password)
            user_rec = user.get_user()

            uid = user_rec.sub
            usertype = user_rec._data['custom:usertype']

            userObj = Users.get(uid)
            # userObj = Users.get(uid, usertype)

            out = SerializeUserObj(userObj)
            # out["usertype"] = usertype
            data = {
                # "idToken": user.id_token,
                "accessToken": user.access_token,
                # "refreshToken": user.refresh_token,
                "profile": out
            }
            res = GetResponseObject(data, 200, True)
            res.headers['HMS-TOKEN'] = "Bearer " + user.access_token
            # res.set_cookie(settings.COOKIE_NAME , user.access_token)
            return res

        except Exception as e:
            msg = f"Error while authenticating user {str(e)}"
            return GetResponseObject(msg)
            # return HttpResponseServerError(res)
    else:
        data = f"Invalid request method, method {request.method} not supported !!!"
        return GetResponseObject(data, 405)
Esempio n. 9
0
    def get_user(user_id):
        cursor = connection.cursor()
        try:
            cursor.execute(dbqueries.get_user, [user_id])
            results = DBManager.named_tuple_fetchall(cursor)

            if results is None:
                return None
            else:
                dict_user = results[0]

                user = Users()

                user.user_id = dict_user.USER_ID
                user.password = dict_user.PASSWORD
                user.email_address = dict_user.EMAIL_ADDRESS
                user.first_name = dict_user.FIRST_NAME
                user.last_name = dict_user.LAST_NAME
                user.is_admin = dict_user.IS_ADMIN
                return user
        except Exception as error:
            return None
        finally:
            cursor.close()
Esempio n. 10
0
    def authenticate_user(email_address, password):
        cursor = connection.cursor()
        try:
            cursor.execute(dbqueries.authenticate_user,
                           [email_address, password])
            results = DBManager.named_tuple_fetchall(cursor)

            if len(results) == 0:
                return None
            else:
                dict_user = results[0]
                print(dict_user)
                user = Users()
                user.user_id = dict_user.USER_ID
                user.password = dict_user.PASSWORD
                user.email_address = dict_user.EMAIL_ADDRESS
                user.first_name = dict_user.FIRST_NAME
                user.last_name = dict_user.LAST_NAME
                user.is_admin = dict_user.IS_ADMIN
                return user
        # except Exception as error:
        #     return None
        finally:
            cursor.close()
Esempio n. 11
0
    def post(self, request):
        data = json.loads(request.body)

        email = data['email']
        if not email:
            return self.response(message='이메일을 입력해주세요', status=400)

        input_password = data['password']
        if not input_password:
            return self.response(message='비밀번호를 입력해주세요', status=400)

        user = Users.objects.filter(email=email)
        if not user:
            return self.response(message='이메일과 비밀번호를 확인해주세요', status=400)

        user = Users.objects.get(email=email)

        try:
            result = Users.check_password(hashed_password=user.password,
                                          input_password=input_password)
            if not result:
                return self.response(message='이메일과 비밀번호를 확인해주세요', status=400)
            if not user.is_active:
                return self.response(message='휴면계정입니다. 관리자에게 문의해주세요',
                                     status=400)
        except KeyError:
            return self.response({}, "INVALID_KEY", 400)

        access_token = generate_token(user_id=user.pk, nickname=user.nickname)

        response = JsonResponse({'data': {
            'id': user.pk,
            'email': user.email
        }},
                                status=200)
        response = set_token(response, access_token)
        return response
Esempio n. 12
0
    def get(self, request, sns_type):
        naver = NaverClient()
        kakao = KakaoClient()

        try:
            # 2. 인증 완료후 소셜 로그인 페이지에서 권한 증서(code grant)를 받아옵니다.
            code = request.GET.get('code')

            if sns_type == 'kakao':
                token_json = kakao.get_access_token(code)
                error = token_json.get('error', None)
                if error is not None:
                    self.response(message='INVALID_CODE', status=400)

                try:
                    access_token = token_json.get('access_token')

                    # 4. oauth 서버에서 유저 정보(token and profile)를 받아옵니다.
                    sns_info_json = kakao.get_profile(
                        access_token=access_token)

                    sns_id = sns_info_json.get('id')

                    kakao_account = sns_info_json.get('kakao_account')
                    email = kakao_account.get('email')
                    kakao_profile = kakao_account.get('profile')
                    nickname = kakao_profile.get('nickname')

                except KeyError:
                    self.response(message='INVALIDd_TOKEN', status=400)

            if sns_type == 'naver':
                token_json = naver.get_access_token(code)
                error = token_json.get("error", None)
                if error is not None:
                    self.response(message='INVALID_CODE', status=400)

                try:
                    access_token = token_json.get('access_token')

                    # 4. oauth 서버에서 유저 정보(token and profile)를 받아옵니다.
                    sns_response = naver.get_profile(access_token=access_token)

                    if not sns_response[0]:
                        return self.response(message='유저 정보 받아오는데 실패했습니다.',
                                             status=400)

                    sns_id = sns_response[1].get('id')
                    email = sns_response[1].get('email')
                    nickname = sns_response[1].get('nickname')

                except KeyError:
                    self.response(message='INVALID_TOKEN', status=400)

        except KeyError:
            self.response(message='INVALID_CODE', status=400)

        # back-end: 5. 서버가 db에 고유 id를 보내서 회원을 인증합니다.
        # 5-1. 회원이라면 일반적인 로그인과정을 진행합니다.
        if Users.objects.filter(sns_type=sns_type, sns_id=sns_id).exists():
            user = Users.objects.get(sns_type=sns_type, sns_id=sns_id)
        else:  # 5-2. 회원이 아니라면 회원가입을 진행합니다.
            user = Users(sns_type=sns_type,
                         email=email,
                         nickname=nickname,
                         sns_id=sns_id,
                         sns_connect_date=datetime.datetime.now())
            user.save()
            user.update(is_active=True)
        access_token = generate_token(user_id=user.pk, nickname=user.nickname)

        response = JsonResponse({'data': {
            'id': user.pk,
            'email': user.email
        }},
                                status=200)
        response = set_token(response, access_token)
        return response
Esempio n. 13
0
    def form_valid(self, form):
        """
        If the form is invalid, re-render the context data with the
        data-filled form and errors.
        """
        transaction.set_autocommit(False)
        try:
            user = Users()
            user.username = form.cleaned_data['login_id']
            user.email = Users.objects.normalize_email(
                form.cleaned_data['email'])
            user.set_password(form.cleaned_data['password'])
            user.user_group_id = int(form.cleaned_data['level'])
            irric_user = IrricUser()
            irric_user.name = form.cleaned_data['name']
            irric_user.furigana = form.cleaned_data['furigana']
            if form.cleaned_data["password_reset_next_login_flag"] is True:
                user.is_force_password_change = True

            now = timezone.now()
            user.created_user_id = self.request.user.id
            user.updated_user_id = self.request.user.id
            user.created_at = now
            user.updated_at = now
            irric_user.created_user_id = self.request.user.id
            irric_user.updated_user_id = self.request.user.id
            irric_user.created_at = now
            irric_user.updated_at = now

            irric_user.save()

            user.irric_user_id = irric_user.id
            user.save()

            if form.cleaned_data["send_mail_flag"] is True:
                # TODO IRRICユーザー作成後にメール送信
                pass

        except Exception as e:
            logger.exception(e)
            transaction.rollback()
            return self.form_invalid(form)

        finally:
            transaction.commit()
            transaction.set_autocommit(True)

        return super().form_valid(form)