def registration(request):
    context = dict()
    context['form'] = RegistrationForm
    context.update(csrf(request))
    if request.POST:
        form = RegistrationForm(request.POST)
        context['form'] = form
        if form.is_valid():
            form.save()  # save user to database if form is valid

            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
            salted_email = salt + email
            activation_key = hashlib.sha1(salted_email.encode('utf-8')).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            # Get new user by username
            new_user = User.objects.get(username=username)

            # Create and save user profile
            new_profile = UserProfile(user=new_user, activation_key=activation_key, key_expires=key_expires)
            new_profile.save()

            # Send email with activation key
            email_subject = 'Account confirmation'
            email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
            48hours http://127.0.0.1:8000/user/confirm/%s" % (username, activation_key)

            send_mail(email_subject, email_body, '*****@*****.**', [email], fail_silently=False)

            return redirect('user.views.login')
        else:
            context['form'] = form
    return render(request, "registration.html", context)
Exemple #2
0
def register_user(request):
    context = RequestContext(request)
    print("registration started")

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        cpassword = request.POST['cpassword']
        roll_no = request.POST['roll_no']
        email = request.POST['email']
        if str(password) == str(cpassword):
            try:
                print("creating user")
                user = User.objects.create_user(username, email, password)
                print("creating userprofile")
                userprof = UserProfile(user.id, roll_no)
                print("created userprofile")
            except TypeError:
                return HttpResponse("Error Processing Request")
            else:
                print("saving user")
                user.save()
                print("saving profile")
                userprof.save()
            return render_to_response('login.html', context)
        elif str(password) != str(cpassword):
            return HttpResponse("password mismatch")
    return render_to_response('register.html', context)
Exemple #3
0
class DeleteUserTest(TestCase):
    def setUp(self):
        self.userprofile = UserProfile()
        self.userprofile.name("Gustavo Rodrigues Coelho")
        self.userprofile.registration_number = "110030559"
        self.userprofile.category = 'Student'
        self.userprofile.user.username = "******"
        self.userprofile.user.email = "*****@*****.**"
        self.userprofile.user.set_password('123456')
        self.userprofile.save()
        self.client = Client()
        self.factory = RequestFactory()
        self.url = '/user/delete/'

    def test_get_request_logged(self):
        client = self.client
        client.login(username='******', password='******')
        response = self.client.get(self.url, follow=True)
        self.assertTemplateUsed(response, 'SistemaGestao/index.html')
        self.assertEqual(response.status_code, 200)

    def test_get_request_anonymous(self):
        response = self.client.get(self.url, follow=True)
        self.assertTemplateUsed(response, 'SistemaGestao/index.html')
        self.assertEqual(response.status_code, 200)

    def test_delete_user(self):
        client = self.client
        client.login(username='******', password='******')
        self.client.get(self.url, follow=True)
        self.assertEqual(False,
                         UserProfile.objects.filter(
                             registration_number="110030559").exists())
Exemple #4
0
def registration(operation,
                 phone,
                 OTP=None,
                 first_name=None,
                 last_name=None,
                 email=None,
                 password=None):
    if operation == 'VERIFY_USER_REGISTRATION_SEND_OTP':
        data = UserProfile.phone_input(operation, phone)
        context = {'user_registered': data['user_registered']}
        return context
    elif operation == 'USER_SIGNIN':
        data = get_user_from_phone(phone=phone,
                                   phone_otp=OTP,
                                   password=password)
        return data
    elif operation == 'USER_SIGNUP':
        user = UserProfile.create_with_phone(phone=phone,
                                             otp=OTP,
                                             email=email,
                                             first_name=first_name,
                                             last_name=last_name).user
        if password:
            user.set_password(password)
            user.save()
        token = jwt_utils.get_token_for_user(user)
        data = {'username': user.username, 'token': token, 'user_id': user.id}
        return data
Exemple #5
0
def signup_form(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save() #completed sign up
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            # Create data in profile table for user
            current_user = request.user
            data=UserProfile()
            data.user_id=current_user.id
            data.save()
            messages.success(request, 'Ваш аккаунт создан!')
            return HttpResponseRedirect('/')
        else:
            messages.warning(request,form.errors)
            return HttpResponseRedirect('/signup')


    form = SignUpForm()
    category = Category.objects.all()
    context = {'category': category,
               'form': form,
               }
    return render(request, 'user/signup_form.html', context)
Exemple #6
0
def register(request):
	if request.method == "POST":
		#Usual test cases
		if User.objects.filter(username=request.POST['user_reg']).exists():
			return render(request, 'user/login.html',{'usr':"******"})
		elif User.objects.filter(email=request.POST['email']).exists():
			return render(request, 'user/login.html',{'usr':"******"})
		elif request.POST['password'] != request.POST['password2']:
			return render(request, 'user/login.html',{'pwd':" <h4 class='text-danger'>Both the passwords don't match.</h4>"})
		else:
			#Validate the password
			try:
				validate_password(request.POST['password'])
			except ValidationError as e:
				return render(request, 'user/login.html',{'pwd':password_validators_help_text_html()})
			#Yay, new user
			user = User.objects.create_user(request.POST['user_reg'],request.POST['email'],request.POST['password'])
			#comm = Communities.objects.get(name='users')
			profile = UserProfile(user=user)
			profile.save()
			user = authenticate(username=request.POST['user_reg'], password=request.POST['password'])
			auth.login(request, user)
			return render(request,'user/profile.html')
	else:
		return render(request,"user/login.html")
Exemple #7
0
def register_user(request):
    context = RequestContext(request)
    print("registration started")

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        cpassword = request.POST['cpassword']
        roll_no = request.POST['roll_no']
        email = request.POST['email']
        if str(password) == str(cpassword):
            try:
                print("creating user")
                user = User.objects.create_user(username, email, password)
                print("creating userprofile")
                userprof = UserProfile(user.id, roll_no)
                print("created userprofile")
            except TypeError:
                return HttpResponse("Error Processing Request")
            else:
                print("saving user")
                user.save()
                print("saving profile")
                userprof.save()
            return render_to_response('login.html')
        elif str(password) != str(cpassword):
            return HttpResponse("password mismatch")
    return render_to_response('register.html', context)
Exemple #8
0
def register_action(request):
    context = {}
    if request.method == "GET":
        return render(request, 'register.html')

    form = UserRegisterForm(request.POST)
    context["registerForm"] = form
    if not form.is_valid():
        print("User Registration Form is invalid ...")
        return render(request, 'register.html', context)

    print("User Registration Form is valid.")
    username, email = form.cleaned_data['username'], form.cleaned_data['email']
    password = form.cleaned_data['password1']
    user = User.objects.create_user(username=username,
                                    email=email,
                                    password=password)
    user.save()
    profile = UserProfile(user=user, good=0, fair=0, bad=0)
    profile.save()
    cart = ShoppingCart(user=user)
    cart.save()
    sendEmail(email) # send registration email

    print("New user is created but not activated.")
    return redirect('/login')
Exemple #9
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email', '')
            nick_name = request.POST.get('nick_name', '')
            pass_word = request.POST.get('password', '')
            retype_password = request.POST.get('retype_password', '')
            if UserProfile.objects.filter(email=email):  # 检查是否已经注册过该用户
                return render(request, 'register.html', {'register_form': register_form, 'msg': '邮箱已存在!'})
            elif UserProfile.objects.filter(nick_name=nick_name):  # 检查是否已经注册过该用户
                return render(request, 'register.html', {'register_form': register_form, 'msg': '昵称已存在!'})
            elif pass_word != retype_password:
                return render(request, 'register.html', {'register_form': register_form, 'msg': '两次密码不一样'})
            else:
                user_profile = UserProfile()
                user_profile.nick_name = nick_name
                user_profile.username = email
                user_profile.email = email
                user_profile.password = make_password(pass_word)
                user_profile.is_active = True
                # user_profile.is_active = False  # 未激活
                # send_email_register(user_name)  # 发送邮件
                user_profile.save()

                # # 写入欢迎注册消息
                # user_message = UserMessage()
                # user_message.user = user_profile.id
                # user_message.message = '欢迎注册'
                # user_message.save()
                return render(request, 'login.html')
        else:
            return render(request, 'register.html', {'register_form': register_form})
Exemple #10
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        print(register_form.data)
        if register_form.is_valid():
            user_name = request.POST.get('username', None)
            if UserProfile.objects.filter(username=user_name):
                return render(request, 'users/Regist.html', {
                    'register_form': register_form,
                    'msg': '用户已存在'
                })

            password1 = request.POST.get('password1', None)
            password2 = request.POST.get('password2', None)
            email = request.POST.get('email', None)
            tel = request.POST.get('tel', None)
            if password1 == password2:
                user_profile = UserProfile()
                # 实例化UserProfile对象
                user_profile.username = user_name
                user_profile.email = email
                user_profile.mobile = int(tel)

                user_profile.is_active = False

                user_profile.password = make_password(password1)
                user_profile.save()
                send_register_email(email)
                return render(request, 'users/Login.html')
            else:
                return render(request, 'users/Regist.html',
                              {'register_form': register_form})
        else:
            return render(request, 'users/Regist.html',
                          {'register_form': register_form})
Exemple #11
0
def user_register(request):
    if request.method == 'GET':
        user_register_form = UserRegisterForm()
        return render(request, 'register.html',
                      {'user_register_form': user_register_form})
    else:
        user = UserRegisterForm(request.POST)
        if user.is_valid():
            username = user.cleaned_data['username']
            email = user.cleaned_data['email']
            password = user.cleaned_data['password']
            u = UserProfile.objects.filter(
                Q(username=username) | Q(email=email))
            if u:
                return render(request, 'register.html', {'msg': '此用户名或邮箱已被注册'})
            else:
                user_profile = UserProfile()
                user_profile.email = email
                user_profile.username = username
                user_profile.set_password(password)
                user_profile.is_active = 0
                user_profile.save()
                send_email(email, 'register')
                return HttpResponse(
                    '注册成功,去激活吧! <a href="http://123.56.23.97">回到首页</a>')
        else:
            return render(request, 'register.html',
                          {'user_register_form': user})
Exemple #12
0
 def setUp(self):
     self.userprofile = UserProfile()
     self.userprofile.name("Gustavo Rodrigues Coelho")
     self.userprofile.registration_number = "110030559"
     self.userprofile.category = 'Student'
     self.userprofile.user.username = "******"
     self.userprofile.user.email = "*****@*****.**"
     self.userprofile.user.set_password('123456')
     self.userprofile.save()
     self.client = Client()
     self.factory = RequestFactory()
Exemple #13
0
def profile(request):
	user = User.objects.get(username=request.user)
	#If signed up via OAuth
	if UserProfile.objects.filter(user__username=request.user).exists() == False:
		profile = UserProfile(user=request.user)
		profile.save()
	profile = UserProfile.objects.get(user=request.user)
	existing_files = profile.files_set.all().order_by('file_name').values()
	friend_requests = profile.requests.all().values('req_from__user__username')
	#comm = profile.comm
	return render(request, 'user/profile.html',{'user':user,'profile':profile,
		'file':existing_files,'friend_requests':friend_requests})
Exemple #14
0
def create_one_time_profile(post, temp_user=User()):
    """
    Function to create a new one-time contributing user
    :param temp_user: user object to populat
    :param post: dictionary (usually request.POST) with new user details
    :return: a new one-time user
    """
    # get first language details.
    try:
        first_lang_code = post.get('first_language', 'x')
        first_lang = Language.objects.get(code=first_lang_code)
    except ObjectDoesNotExist as e:
        raise e

    # try get second language
    try:
        sec_lang_code = post.get('second_language', 'x')
        second_lang = Language.objects.get(code=sec_lang_code)
    except ObjectDoesNotExist:
        second_lang = None

    # try get third language
    try:
        third_lang_code = post.get('third_language', 'x')
        third_lang = Language.objects.get(code=third_lang_code)
    except ObjectDoesNotExist:
        third_lang = None

    # try get the age
    try:
        age = int(post.get('age', '?'))
    except ValueError:
        age = 0

    # save user to generate a new pk
    temp_user.username = '******' \
                         + str(uuid.uuid4()) + '_' + str(uuid.uuid4())
    temp_user.is_active = False
    temp_user.set_password(str(uuid.uuid4()))
    temp_user.save()

    # create user profile
    temp_profile = UserProfile(
        user=temp_user,
        age=age,
        first_language=first_lang,
        second_language=second_lang,
        third_language=third_lang
    )
    temp_profile.save()
    # create unique username

    return temp_user
Exemple #15
0
 def post(self, request):
     register_form = RegisterForm(request.POST)
     if register_form.is_valid():
         email = request.POST.get("email", '')
         if UserProfile.objects.filter(email=email):
             return render(request, 'register.html', {
                 'register_form': register_form,
                 'msg': '用户已存在'
             })
         pass_word = request.POST.get("password", '')
         user_name = request.POST.get("username", '')
         if UserProfile.objects.filter(username=user_name):
             return render(request, 'register.html', {'msg': '此用户名已被使用'})
         user_profile = UserProfile()
         user_profile.username = user_name
         user_profile.email = email
         user_profile.is_active = False
         user_profile.password = make_password(pass_word)
         user_profile.save()
         send_email_register(email, 'register')
         return render(request, 'login_user.html',
                       {'msg': "发送邮件成功,请注意查收..."})
     else:
         email = request.POST.get("email", '')
         return render(request, 'register.html', {
             'email': email,
             'register_form': register_form
         })
def signup_form(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()  # completed sign up
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            language = Language.objects.get(code=request.LANGUAGE_CODE[0:2])
            login(request, user)
            # Create data in profile table for user
            current_user = request.user
            data = UserProfile()
            data.user_id = current_user.id
            data.image = "images/users/user.png"
            data.language_id = language.id
            data.currency_id = request.session['currency']
            data.save()
            messages.success(request, 'Ваш аккаунт успешно создан!')
            return HttpResponseRedirect('/')
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect('/signup')
    form = SignUpForm()
    #category = Category.objects.all()
    context = {  #'category': category,
        'form': form,
    }
    return render(request, 'signup_form.html', context)
Exemple #17
0
def signup(request):
	error = [False, '']
	form = SignUpForm()
	if request.method == 'POST':
		form = SignUpForm(request.POST)		
		userdata = (request.POST['username']).split()
		username = userdata[0]
		first_name = userdata[1]
		last_name = userdata[2]
		mail = request.POST['mail']
		password1 = request.POST['password1']
		password2 = request.POST['password2']
		if form.is_valid() and password1 == password2 and len(password1) >= 6:
			user = User.objects.create_user(username, mail, password1)
			user.first_name = first_name
			user.last_name = last_name
			user.is_active = True
			user.save()	
			userprofile = UserProfile()
			userprofile.user = user
			userprofile.vk = ''
			userprofile.facebook = ''
			userprofile.twitter = ''
			userprofile.phone = ''
			userprofile.save()
			# Добавление действия в ленту
			addAction(user, 'присоединился к сервису')	
			setAch(user, 1)
			return redirect('/auth/in')
		else:
			print('form not valid!')
			error[0] = True
			error[1] = 'Введенные данные содержат ошибку'	
	context = {"form": form, 'title': 'Регистрация', 'error': error[0], 'error_text': error[1]}
	return render(request, 'sign-up.html', context)
Exemple #18
0
    def post(self, request):
        re_form = ReForm(request.POST)
        #验证是否通过
        if re_form.is_valid():
            email = request.POST.get('email', '')
            password = request.POST.get('password', '')

            #判断是否相同邮箱
            emails = UserProfile.objects.filter(email=email)
            if emails:
                return render(request, 'lw-re.html', {
                    're_form': re_form,
                    'msg': '邮箱已经被注册'
                })
            else:
                add_user = UserProfile()
                add_user.username = email
                add_user.email = email
                add_user.is_active = False
                # 加密密码进行保存
                add_user.password = make_password(password)
                add_user.save()

                #发激活邮件给用户
                send_email(email, 'register')
                return render(request, 'lw-log.html', {'msg': '激活邮件已发送'})
        else:
            return render(request, 'lw-re.html', {'re_form': re_form})
Exemple #19
0
    def post(self, request):
        register_form = RegisterForms(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email', None)
            # 如果用户已存在,则提示错误信息
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {
                    'register_form': register_form,
                    'msg': '用户已存在'
                })

            pass_word = request.POST.get('password', None)
            # 实例化一个user_profile对象
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.is_active = False  # 用户未激活
            # 对保存到数据库的密码加密
            user_profile.password = make_password(pass_word)
            user_profile.save()
            send_register_eamil(user_name, 'register')
            return render(request, 'login.html')
        else:
            return render(request, 'register.html',
                          {'register_form': register_form})
Exemple #20
0
def create_super_user():
    try:
        user = UserProfile.objects.get(email='*****@*****.**')
    except Exception as e:
        user = UserProfile()
        user.username = '******'
        user.email = '*****@*****.**'
        user.password = make_password('qwer1234')
        user.is_superuser = True
        user.is_staff = True
        user.save()
Exemple #21
0
def make_token(user: UserProfile, expire=3600 * 24):
    login_datetime = datetime.datetime.now()
    # 修改token
    login_time = time.mktime(login_datetime.timetuple())
    # 修改数据库
    user.login_time = login_datetime
    user.save()
    # 一般使用 用户名/登录时间 来生成token,用来校对
    payload = {
        'phonenumber': user.phonenumber,
        'exp': login_time + expire,
        'login_time': login_time
    }
    return jwt.encode(payload, mysettings.Token_key,
                      algorithm='HS256').decode()
Exemple #22
0
def get_user_from_phone(phone, password=None, phone_otp=None):
    if not password and not phone_otp:
        raise_error('ERR-AUTH-INVALID-CREDENTIALS')

    phone_data = validate_get_phone(phone)
    user_profile = UserProfile.match_user_from_phone(
        phone_number=phone_data['phone_number'],
        phone_code=phone_data['phone_code'])

    if user_profile is None:
        raise_error('ERR-USER-NOT-FOUND')

    user = user_profile.user
    if password and user.check_password(password):
        token = jwt_utils.get_token_for_user(user)
        data = {
            'token': token,
            'user_id': user.id,
            'username': user.username,
            'user': user
        }
        return data
    elif phone_otp and Phone.get_otp(
            phone_number=phone_data['phone_number'],
            phone_code=phone_data['phone_code']) == phone_otp:
        token = jwt_utils.get_token_for_user(user)
        data = {
            'token': token,
            'user_id': user.id,
            'username': user.username,
            'user': user
        }
        return data
    else:
        raise_error('ERR-AUTH-INVALID-PASSWORD')
def home(request):
    if request.method == 'GET':
        return render(request, 'page1.html')
    if request.method == 'POST':
        f_name = request.POST.get('f_name')
        l_name = request.POST.get('l_name')
        contact = request.POST.get('contact')
        email_id = request.POST.get('email_id')
        gender = request.POST.get("gender")
        profile = UserProfile(f_name=f_name,
                              l_name=l_name,
                              ph_no=contact,
                              email=email_id,
                              gender=gender)
        profile.save()
        return redirect('home')
Exemple #24
0
def auth_signup(first_name,
                last_name,
                password1,
                password2,
                otp=None,
                email=None,
                phone=None,
                username=None,
                phone_otp=None,
                email_otp=None):
    if password1 != password2:
        raise_error('ERR-AUTH-UNMATCHED-PASSWORD')

    user = UserProfile.create(phone=phone,
                              email=email,
                              first_name=first_name,
                              last_name=last_name,
                              username=username,
                              phone_otp=phone_otp,
                              email_otp=email_otp).user
    user.set_password(password1)
    user.save()
    token = jwt_utils.get_token_for_user(user)
    data = {'username': user.username, 'token': token, 'user_id': user.id}
    return data
Exemple #25
0
 def wrapper(request, *args, **kwargs):
     token = request.META.get('HTTP_AUTHORIZATION')
     print(token)
     if request.method not in methods:
         return func(request, *args, **kwargs)
     if not token:
         result = {'code': 101, 'error': 'give me token'}
         return JsonResponse(result)
     try:
         res = jwt.decode(token, key, algorithms=['HS256'])
     except jwt.ExpiredSignatureError:
         result = {'code': 108, 'error': 'Please login'}
         return JsonResponse(result)
     except Exception as e:
         result = {'code': 109, 'error': 'Please login'}
         return JsonResponse(result)
     print('res', res)
     username = res['username']
     try:
         user = UserProfile(username=username)
     except:
         user = None
     if not user:
         result = {'code': 110, 'error': 'no user'}
         return JsonResponse(result)
     request.user = user
     return func(request, *args, **kwargs)
Exemple #26
0
def get_or_create_user_from_google(data):
    try:
        data['id']
        data['id_token']
        data['email']
    except KeyError:
        raise_error()

    try:
        google = UserGoogleData.objects.get(uid=data['id'])
        google.update(extra_data=data)
        user = google.user_profile.user
    except UserGoogleData.DoesNotExist:
        try:
            # If the user's email already exists in our DB, then just associate that user with the Google data
            user_profile = UserProfile.objects.get(
                user__email__iexact=data['email'])
            user = user_profile.user
        except UserProfile.DoesNotExist:
            # No data related to the user exists on our DB - so create the User, record the Data
            user = UserProfile.create(email=data['email'],
                                      first_name=data['first_name'],
                                      last_name=data['last_name']).user

        UserGoogleData.create(user=user, data=data)

    if user and user.is_active:
        token = jwt_utils.get_token_for_user(user)
        return token
    else:
        raise_error(code='ERR0006')
Exemple #27
0
    def __init__(self, user=None, *args, **kwargs):
        super(BookingForm, self).__init__(*args, **kwargs)
        self.fields['responsible'] = forms.CharField(
            label=_('Responsible (optional):'),
            required=False,
            widget=forms.widgets.Select(
                attrs={'class': 'selectize'},
                choices=UserProfile.get_users(),
            ))

        self.fields['tags'] = forms.CharField(
            label=_('Tags (optional):'),
            required=False,
            widget=forms.widgets.SelectMultiple(
                attrs={'class': 'selectize_multiple'},
                choices=Tag.get_tags(),
            ))

        try:
            if not (user and user.profile_user.is_admin()):
                self.fields.pop('engineering_choice')
                self.fields.pop('responsible')
        except:
            self.fields.pop('engineering_choice')
            self.fields.pop('responsible')
Exemple #28
0
 def create(self, request, *args, **kwargs):
     username = request.data.get("username", "")
     password = request.data.get("password", "")
     checkpass = request.data.get("checkpass", "")
     email = request.data.get("email", "")
     captcha_code = request.data.get("captcha_code", "")
     hashkey = request.data.get("hashkey", "")
     get_setting_info = get_setting_config()
     if not username:
         return JsonResponse({"code": 400, "msg": "用户名不能为空"})
     if UserProfile.objects.filter(username=username).count():
         return JsonResponse({"code": 400, "msg": "该用户已被注册"})
     if not email:
         return JsonResponse({"code": 400, "msg": "邮箱不能为空"})
     if UserProfile.objects.filter(email=email, has_active=True).count():
         return JsonResponse({"code": 400, "msg": "该邮箱已被注册"})
     if not captcha_code:
         return JsonResponse({"code": 400, "msg": "验证码不能为空"})
     if not judge_captcha(captcha_code, hashkey):
         return JsonResponse({"code": 400, "msg": "验证码错误"})
     if password != checkpass:
         return JsonResponse({"code": 400, "msg": "两次密码输入不一致"})
     code = generate_code(6)
     keys = red_user_cache.keys()
     for single_key in keys:
         try:
             single_user_info = red_user_cache.get(single_key)
             redis_username, redis_password, redis_email = json.loads(
                 single_user_info)
             if username == redis_username:
                 return JsonResponse({"code": 400, "msg": "该用户已被注册"})
             if redis_email == email:
                 return JsonResponse({"code": 400, "msg": "该邮箱已被注册"})
         except Exception as e:
             return JsonResponse({"code": 400, "msg": "用户注册失败"})
     if get_setting_info['cancel_validation'] == False:
         user = UserProfile(username=username, email=email)
         user.set_password(password)
         user.has_active = True
         user.greenhand = True
         user.save()
         return JsonResponse({"code": 200, "msg": "注册成功"})
     try:
         send_activate_email(receiver_email=email,
                             code=code,
                             request=request)
     except smtplib.SMTPDataError as e:
         return JsonResponse({"code": 400, "msg": "邮件发送失败,请减缓发送频率"})
     except Exception as e:
         return JsonResponse({"code": 400, "msg": "邮件发送失败"})
     try:
         user_info = [username, password, email]
         red_user_cache.set(code, json.dumps(user_info), ex=300)
     except Exception as e:
         return JsonResponse({"code": 400, "msg": "注册失败"})
     return JsonResponse({"code": 200, "msg": "注册用户成功,请到邮箱激活您的账号"})
Exemple #29
0
 def post(self, request):
     form = SignUpForm(request.POST)
     if form.is_valid():
         form.save()
         username = form.cleaned_data.get('username')
         raw_password = form.cleaned_data.get('password1')
         user = authenticate(username=username, password=raw_password)
         login(request, user)
         form1 = UserProfile(phone_number='',
                             address='',
                             alternate_email='',
                             owner=user)
         form1.save()
         return redirect('home:all')
     else:
         ctx = {'form': form}
         return render(request, 'user/signup.html', ctx)
Exemple #30
0
 def userProfileFromRequest(self, requestParam):
     tempProfile = UserProfile()\
                                     .configID(requestParam.get('username'), requestParam.get('source')) \
                                     .configName(requestParam.get('name'))\
                                     .configEmail(requestParam.get('email'),
                                                                     self.get_role(requestParam.get('role'))) \
                                     .configCreatedOn(None)
     return tempProfile
Exemple #31
0
 def userProfileFromRequest(self, params):
     temp_profile = UserProfile()\
                                     .configID(params.get('username'), params.get('source'))\
                                     .configName(params.get('name'))\
                                     .configEmail(params.get('email'),
                                     self.get_role(params.get('role')))\
                                     .configCreatedOn(None)
     return temp_profile
    def create_users_pdf(self, user):
        museum = self.cleaned_data['museum']
        name = self.cleaned_data['name']

        group = Group(museum=museum, name=name, created_by=user)
        group.save()
        tokens = []
        for x in range(self.cleaned_data['number']):
            profile = UserProfile()
            profile.display_name = f'space cadet {x + 1}'
            profile.save()
            group.profiles.add(profile)
            museum.profiles.add(profile)
            tokens.append(profile.qr_token)

        group.save()
        museum.save()
Exemple #33
0
    def create(self, validated_data):
        print('======validated_data=======', validated_data)

        user = UserProfile()
        user.username = validated_data['username']
        user.mobile = validated_data['username']
        user.set_password(validated_data['password'])

        user.save()
        return user
Exemple #34
0
def register_user(step, username, password, registration_number):
    user = UserProfile()
    user.user = User()
    user.registration_number = registration_number
    user.user.email = username
    user.user.username = username
    user.user.first_name = "Usuário"
    user.user.set_password(password)
    user.save()
    user.make_as_academic_staff()
def signup(request):    
    if request.method == "POST":
        first_name = request.POST.get("first_name")
        last_name = request.POST.get("last_name")
        username = request.POST.get("username")
        email = request.POST.get("email")
        password = request.POST.get("password")
        user = User.objects.create_user( first_name=first_name, last_name=last_name,username=username,email=email,password=password)
        user.save()
        created_user = authenticate(username=username, password=password)
        login(request, created_user)
        #Create data in profile table for user
        current_user = request.user
        data = UserProfile()
        data.user_id = current_user.id
        data.name = last_name
        data.image="images/users/user.png"
        data.save()

        messages.success(request, 'Your account has been created!')
        return HttpResponseRedirect('/')
    
    setting = Setting.objects.all()
    catagories = ProductCategories.objects.all()
    context = {
        "catagories":catagories,
        "setting":setting,
    }
    return render(request, 'user_create.html',context=context)
Exemple #36
0
def signup(request):
    try:
        if request.method == 'POST':
            form = RegisterForm(request.POST) # A form bound to the POST data
            form.full_clean()
            if form.is_valid():
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                user = User.objects.create_user(username, email, password)
                user.first_name = form.cleaned_data['first_name']
                user.last_name = form.cleaned_data['last_name']

                new_profile = UserProfile(user=user)
                new_profile.ezweb_url = settings.EZWEB_URL

                if settings.REGISTRATION_CONFIRMATION:
                    user.is_active = False

                    salt = hashlib.sha224(str(random.random())).hexdigest()[:5]
                    activation_key = hashlib.sha224(salt+user.username).hexdigest()
                    key_expires = datetime.datetime.today() + datetime.timedelta(settings.ACCOUNT_ACTIVATION_DAYS)
                    new_profile.activation_key=activation_key
                    new_profile.key_expires=key_expires

                    confirm_url = request.build_absolute_uri('/confirm/' + new_profile.activation_key)
                    email_subject = _("Your new FAST account confirmation")
                    email_body = _("Hello, %s, and thanks for signing up for an FAST account.\n\nTo activate your account, click this link within %s days:\n\n%s") % (user.username, settings.ACCOUNT_ACTIVATION_DAYS, confirm_url)

                    email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.REGISTRATION_SENDER, to = [user.email])
                    email.send()

                user.save()
                new_profile.save()

                user = authenticate(username=username, password=password)
                if user.is_active:
                    login(request, user)
                    return render_to_response('index.html',{}, context_instance=RequestContext(request))
                else:
                    return HttpResponseRedirect('/accounts/login/?next=/')

        return render_to_response('registration/register.html',{'form': form},
                  context_instance=RequestContext(request))
    except Exception, e:
        return render_to_response('registration/register.html',{'form': RegisterForm(),},
                  context_instance=RequestContext(request))
Exemple #37
0
 def get(self,request):
     user = self.request.user
     if (user.is_authenticated()):
         profile = UserProfile.create_or_get_profile(user)
Exemple #38
0
                                                           quantity=quantity))

            RecipeIngredients.objects.bulk_create(drink_ingredients)

        create_drink('screwdriver', 120, 40)
        create_drink('gin_and_vodka', 10, 40)

        add_ingredients_to_drink(self.screwdriver, [(Ingredient.objects.get(name='Vodka'), 1),
                                                    (Ingredient.objects.get(name='Orange Juice'), 2)])

        add_ingredients_to_drink(self.gin_and_vodka, [(Ingredient.objects.get(name='Vodka'), 2),
                                                      (Ingredient.objects.get(name='Gin'), 2)])

    def test_create_or_get_profile(self):
<<<<<<< HEAD
        profile = UserProfile.get_or_create_profile(self.user)
=======
        profile = UserProfile.create_or_get_profile(self.user)
>>>>>>> dev
        self.assertEqual(self.profile, profile)
        self.assertEqual('testuser', profile.user.username)
        self.assertEqual('*****@*****.**', profile.user.email)
        self.assertNotEqual('password', profile.user.password)

    def test_set_favorites(self):
        # Test set 1 favorite
<<<<<<< HEAD
        # noinspection PyUnresolvedReferences
=======
>>>>>>> dev
        def set_one_favorite():