def set_password(self, raw_password): """Overridden so that we can keep track of password age""" super(MflUser, self).set_password(raw_password) # Exclude new users ( who have never logged in before ) from this # We rely on this to implement a "change password on first login" # roadblock if self.last_login: if self.password_history: self.password_history.append(make_password(raw_password)) else: self.password_history = [make_password(raw_password)]
def handle(self, *args, **options): chrio = Group.objects.get( name="County Health Records Information Officer") schrio = Group.objects.get( name="Sub County Health Records Information Officer") for county in County.objects.all(): user_data = { "email": "{}@mfltest.slade360.co.ke".format( county.name.lower()), "first_name": "{}".format(county.name.lower()), "last_name": "{}".format(county.name.lower()), "username": "******".format(county.name.lower()), "password": make_password(county.name.lower()), "employee_number": county.code * 825, } try: user_obj = MflUser.objects.get(email=user_data['email']) except MflUser.DoesNotExist: user_obj = MflUser.objects.create(**user_data) try: UserCounty.objects.get(user=user_obj) except UserCounty.DoesNotExist: UserCounty.objects.create( user=user_obj, county=county, created_by=user_obj, updated_by=user_obj) user_obj.groups.add(chrio) for const in Constituency.objects.all(): user_data = { "email": "{}@mfltest.slade360.co.ke".format( const.name.lower()), "first_name": "{}".format(const.name.lower()), "last_name": "{}".format(const.name.lower()), "username": "******".format(const.name.lower()), "password": make_password(const.name.lower()), "employee_number": const.code * 2535, } try: user_obj = MflUser.objects.get(email=user_data['email']) except MflUser.DoesNotExist: user_obj = MflUser.objects.create(**user_data) county_chrio = UserCounty.objects.filter( county=const.county)[0].user try: UserConstituency.objects.get(user=user_obj) except UserConstituency.DoesNotExist: UserConstituency.objects.create( constituency=const, user=user_obj, created_by=county_chrio, updated_by=county_chrio) user_obj.groups.add(schrio)
def set_password(self, raw_password): """Overridden so that we can keep track of password age""" super(MflUser, self).set_password(raw_password) # We rely on this to implement a "change password on first login" # roadblock if self.password_history: self.password_history.append( make_password(raw_password)) if self.is_authenticated else None else: self.password_history = [make_password( raw_password)] if self.is_authenticated else None
def set_password(self, raw_password): """Overridden so that we can keep track of password age""" super(MflUser, self).set_password(raw_password) # We rely on this to implement a "change password on first login" # roadblock if self.password_history: self.password_history.append( make_password(raw_password)) if self.is_authenticated else None else: self.password_history = [make_password(raw_password) ] if self.is_authenticated else None
def set_alternative_password(request): """ View to set the alternative password on a user """ context = {} if request.method == 'POST': form = SetAlternativePasswordForm(request.POST) if form.is_valid(): form.cleaned_data['passphrase'] = \ form.cleaned_data['passphrase'] or \ get_random_string(100) passphrase = form.cleaned_data['passphrase'] salt = form.cleaned_data['salt'] or None alternative_password = make_password(passphrase, salt) ap_entry, created = AlternativePassword.objects.get_or_create( user=request.user, ) ap_entry.alternative_password = alternative_password ap_entry.save() context['alternative_password'] = passphrase else: form = SetAlternativePasswordForm() # An unbound form context['form'] = form return render(request, 'altauth/set_alternative_password.html', context)
def test_syncing_of_students_to_another_group_to_central_server(self): # Addresses issue #2124 of learningequality/ka-lite with self.get_distributed_server() as source: self.register(source) facility_id = source.addmodel(FACILITY_MODEL, name='fac1') old_group_id = source.addmodel(GROUP_MODEL, name='group1', facility_id=facility_id) student_password = make_password('password', '10000', 'sha1') student_id = source.addmodel(FACILITY_USER_MODEL, username='******', password=student_password, group_id=old_group_id, facility_id=facility_id) source.sync() new_group_name = 'should-transfer-here' new_group_id = source.addmodel(GROUP_MODEL, name=new_group_name, facility_id=facility_id) source.modifymodel(FACILITY_USER_MODEL, student_id, group_id=new_group_id) source.sync() student = FacilityUser.objects.get(id=student_id) self.assertEquals(student.group_id, new_group_id)
def setup_admin(): User.objects.create(username='******', password=make_password('admin'), is_staff=True, is_superuser=True, email='*****@*****.**', valid_email=True)
def register_user(request): if request.POST: realname = request.POST.get("first_name","") username = request.POST.get("username","") email = request.POST.get("email","") school = request.POST.get("school",None) klass = request.POST.get("klass",None) password = request.POST.get("password","") rpassword = request.POST.get("rpassword","") sfzjh = request.POST.get("sfzjh","") if password=="": return http.HttpResponse({"code":1,"text":u"密码不能为空!"},content_type="application/json") elif password!=rpassword: return http.HttpResponse({"code":1,"text":u"两次输入的密码不一致!"},content_type="application/json") user = User() user.username = username user.email = email user.first_name = realname user.school = accounts_models.Xuexiao.objects.get(id=school) user.password = make_password(password) user.sfzjh = sfzjh if klass: user.bj = accounts_models.Banji.objects.get(id=klass) try: user.save() return http.HttpResponse(json.dumps({"code":1,u"text":u"用户创建成功!"}),content_type="application/json") except Exception,e: return http.HttpResponse(json.dumps({"code":1,"text":u"班村数据失败!"}),content_type="application/json")
def authenticate(self, username=None, password=None): l = ldap.initialize(settings.LDAP_URL) l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) try: bind = l.simple_bind_s('*****@*****.**' % username, password) except: bind = None finally: l.unbind() if bind: try: user = User.objects.get(username=username.lower()) except User.DoesNotExist: # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from settings.py will. user = User(username=username.lower(), password=make_password(password)) user.is_staff = True user.is_superuser = False user.save() return user return None
def __init__(self, username=None, groupname=None, email=None, shared_apikey=None): self.app_label = 'edc_quota' self.username = username or 'edc_quota' self.groupname = groupname or 'edc_quota_api' self.email = '*****@*****.**' self.shared_apikey = shared_apikey try: self.user = User.objects.get(username=self.username) except User.DoesNotExist: password = str(os.urandom(4)) self.user = User.objects.create( username=self.username, password=make_password(password), email=self.email) try: self.group = Group.objects.get(name=self.groupname) except Group.DoesNotExist: self.group = Group.objects.create(name=self.groupname) for permission in Permission.objects.filter( content_type__app_label=self.app_label).exclude(codename__startswith='delete'): self.group.permissions.add(permission) self.user.groups.add(self.group) if self.shared_apikey: apikey = ApiKey.objects.get(user=self.user) apikey.key = self.shared_apikey apikey.save() self.quotas_created = self.create_client_quotas()
def create_user(self, email, first_name, employee_number, password=None, is_staff=False, **extra_fields): check_password_strength(password) now = timezone.now() validate_email(email) p = make_password(password) email = MflUserManager.normalize_email(email) user = self.model(email=email, first_name=first_name, password=p, employee_number=employee_number, is_staff=is_staff, is_active=True, is_superuser=False, date_joined=now, **extra_fields) user.save(using=self._db) send_email_on_signup(user.id, email, first_name, employee_number, password) return user
def authenticate(model, email, password): """ """ try: salted_password = make_password(password, salt="adfits") user = model.objects.get(email=email, password=salted_password) return user except: return None
def create(self, email, first_name, username, password=None, **extra_fields): now = timezone.now() validate_email(email) p = make_password(password) email = MflUserManager.normalize_email(email) user = self.model(email=email, first_name=first_name, password=p, username=username, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields) user.save(using=self._db) return user
def post(self, request, *args, **kwargs): query_model = kwargs['model'] user_id = request.session['_id'] user_obj = query_model.objects.get(pk=user_id) form = self.form_class(query_model, user_obj.name, request.POST) if form.is_valid(): password = form.cleaned_data['new_password'] new_password = make_password(password, salt="adfits") user_obj.password = new_password user_obj.save() return HttpResponseRedirect(self.get_success_url()) else: return self.form_invalid(form)
def create_user(self, email, first_name, employee_number, password=None, is_staff=False, **extra_fields): check_password_strength(password) now = timezone.now() validate_email(email) p = make_password(password) email = MflUserManager.normalize_email(email) user = self.model(email=email, first_name=first_name, password=p, employee_number=employee_number, is_staff=is_staff, is_active=True, is_superuser=False, date_joined=now, **extra_fields) user.save(using=self._db) send_email_on_signup(user, password) return user
def register(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = make_password(form.cleaned_data['password'], None, 'pbkdf2_sha256') email = form.cleaned_data['email'] User.objects.create(username=username, password=password, email=email) response = HttpResponseRedirect("") # response.set_cookie('username', username, 3600) return response # repassword = form.cleaned_data['repassword'] # User.objects.create(username=username, password=password) else: return HttpResponse("wrong form") else: return HttpResponseRedirect('/accounts/login')
def post(self, request, *args, **kwargs): """ Would help to validate user and login the user. """ data = {} form = self.form_class(request.POST) # import pdb # pdb.set_trace() if form.is_valid(): data['first_name'] = form.cleaned_data['first_name'] data['last_name'] = form.cleaned_data['last_name'] data['email'] = form.cleaned_data['email'] data['username'] = form.cleaned_data['username'] password = form.cleaned_data['password'] password_cnf = form.cleaned_data['password_cnf'] if password == password_cnf: try: data['password'] = make_password(password, salt="blog") user = User.objects.create(**data) except: import sys print sys.exc_value # user.delete() messages.error(request, "Something went wrong. Please try again.") return self.form_invalid(form) else: messages.error(request, "Passwords did not match.") return self.form_invalid(form) if user is not None: user = authenticate(username=data['username'], password=password) login(request, user) request.session['USER_ID'] = user.pk request.session['USER_NAME'] = user.first_name return HttpResponseRedirect(reverse('index')) messages.error(request, "Wrong username and Password combination.") return self.form_invalid(form) else: return self.form_invalid(form)
def post(self, request): modify_form = ModifyForm(request.POST) if modify_form.is_valid(): password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('email') if password1 == password2: print("拿到的email", email) user = UserProfile.objects.get(email=email) print("修改密码获取到的", user) user.password = make_password(password1) user.save() return redirect('/user/login/') else: err = "两次密码输入不一致" return render(request, 'user/reset_password.html', locals()) # 返回重置密码页面 else: return render(request, 'user/reset_password.html', locals()) # 返回表单中验证的错误信息
def register(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = make_password(form.cleaned_data['password'], None, 'pbkdf2_sha256') email = form.cleaned_data['email'] User.objects.create(username=username, password=password, email=email) response = HttpResponseRedirect("") response.set_cookie('username', username, 3600) return response # repassword = form.cleaned_data['repassword'] # User.objects.create(username=username, password=password) else: return HttpResponse("wrong form") else: return HttpResponseRedirect('/accounts/login')
def create(cls, msisdn, name, surname, farmers, markets): """ Create a new Agent. If a user already exists it uses that record. If an agent already exists for that user it returns that, otherwise a new agent is created. :type msisdn: str :type name: str :type surname: str :param farmers: the farmers this agent works with :type farmers: list of magriculture.fncs.models.actors.Farmer :param markets: the markets this agent works in :type markets: list of magriculture.fncs.models.actors.Market :returns: an agent :rtype: magriculture.fncs.models.actors.Agent """ user, created = User.objects.get_or_create(username=msisdn) user.first_name = name user.last_name = surname if created: password = random.randint(1000, 9999) user.password = make_password(password) user.save() actor = user.get_profile() if actor.agent_set.exists(): return actor.as_agent() agent = cls(actor=actor) agent.save() if created: message = "You have been registered and your pin is - %s" % password actor.send_message(actor, message, None) agent.farmers = farmers agent.markets = markets return agent
def create(self, email, first_name, password=None, **extra_fields): now = timezone.now() validate_email(email) p = make_password(password) email = MyUserManager.normalize_email(email) user = self.model(email=email, first_name=first_name, password=p, is_staff=False, is_active=True, is_superuser=False, date_joined=now, **extra_fields) user.save(using=self._db) # # add email device device = TwoFactorEmailDevice.objects.create( user=user, name="Email Device") device.generate_challenge() # add sms device device = TwoFactorPhoneDevice.objects.create( user=user, name="SMS Device", number=user.phone_number, method="sms") device.generate_challenge() return user
def register(request): """ view for reqister :param request: :return: """ if request.method == "POST": user_form = UserForm(request.POST) if user_form.is_valid(): user_name = user_form.cleaned_data['username'] password = user_form.cleaned_data['password'] password_confirm = user_form.cleaned_data['password_confirm'] if password_not_match(password, password_confirm): return HttpResponseRedirect('/errors/pwdnotmatch/') user_form.save() user = User.objects.get(username=user_name) user.password = make_password(user_form.cleaned_data['password']) user.save() return HttpResponseRedirect('/homepage/') else: user_form = UserForm() return render(request, 'registration/register.html', {'user_form': user_form})
def send_mail(request): email = request.POST.get("email") try: user = User.objects.get(email=email) except: return http.HttpResponse(u"请输入注册时使用的邮箱地址!") pk = make_password(u"%s_%s"%(user.username,email),None,"pbkdf2_sha256") user.reset_password = pk; user.save() url = u"%s/rpass/?pk1=%s&pk2=%s"%(request.environ["HTTP_HOST"],base64.b64encode(pk),base64.b64encode(email)) t = u""" <html> <body> <h3>重置用户密码</h3> <p>尊敬的用户您好!<br> 您使用""" + email +u"""邮箱在本站注册了一个用户,您现在请求重置密码。如果不是本人操作,请忽略之,多有打扰清凉解。<br>如果是本人操作,请将链接复制到浏览器地址栏中"""+url+u""" </p> </body> </html> """ sender = u'*****@*****.**' receiver = email subject = u'重置用户密码' username = u'*****@*****.**' password = u'*****@*****.**' msg = MIMEText(t,'html','utf-8') msg['Subject'] = subject smtp = smtplib.SMTP() smtp.connect(u'smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() response_json = {u"code":1,u"text":u"请登陆邮%s箱继续操作"%email} return http.HttpResponse(json.dumps(response_json),content_type=u"application/json")
def save_register_info(self, request, user): """保存用户注册的信息""" username = request.POST.get('username') email = request.POST.get('email') # 在后台再次判断 邮箱和用户名是否已经存在 存在就返回 if UserProfile.objects.filter(Q(username=username) | Q(email=email)): err = "用户名或者邮箱已经存在" return render(request, 'user/register.html', locals()) password1 = request.POST.get('password1') password2 = request.POST.get('password2') allow = request.POST.get('allow') if password1 != password2 or allow != '1': err = '两次输入的密码一致' err_allow = "请阅读用户使用协议" return render(request, 'user/register.html', locals()) user.username = username user.password = make_password(password1) user.email = email user.is_active = False user.save() send_email(email, send_type="注册") return redirect('/user/send_success/')
from django.contrib.auth.models import make_password from django.test import LiveServerTestCase from django.test.utils import override_settings from .utils.crypto_key_factory import KeyFactory from .utils.mixins import CreateAdminMixin, CentralServerMixins from .utils.mixins import FakeDeviceMixin from .utils.distributed_server_factory import DistributedServer from kalite.facility.models import Facility, FacilityGroup, FacilityUser from securesync.models import Device, DeviceZone FACILITY_MODEL = 'kalite.facility.models.Facility' GROUP_MODEL = 'kalite.facility.models.FacilityGroup' FACILITY_USER_MODEL = 'kalite.facility.models.FacilityUser' DUMMY_PASSWORD = make_password('password', '10000', 'sha1') # @override_settings(SYNCING_MAX_RECORDS_PER_REQUEST=10) class SameVersionTests(CreateAdminMixin, CentralServerMixins, FakeDeviceMixin, LiveServerTestCase): def setUp(self): self.setup_fake_device(name="Central") self.user = self.create_admin() self.org = self.create_organization(owner=self.user) self.zone = self.create_zone(organizations=[self.org]) self._key_factory = KeyFactory()
def check_can_unbind_social_account(user): # 用户能否解绑三方代码 if user.password == make_password(None): if UserSocialAuth.objects.filter(user=user).count() == 1: raise NotAllowedToDisconnect(u'只有一个三方账号,不能解绑') return True
from django.contrib.auth.models import make_password from django.test import LiveServerTestCase from django.test.utils import override_settings from .utils.crypto_key_factory import KeyFactory from .utils.mixins import CreateAdminMixin, CentralServerMixins from .utils.mixins import FakeDeviceMixin from .utils.distributed_server_factory import DistributedServer from kalite.facility.models import Facility, FacilityGroup, FacilityUser from securesync.models import Device, DeviceZone FACILITY_MODEL = 'kalite.facility.models.Facility' GROUP_MODEL = 'kalite.facility.models.FacilityGroup' FACILITY_USER_MODEL = 'kalite.facility.models.FacilityUser' DUMMY_PASSWORD = make_password('password', '10000', 'sha1') # @override_settings(SYNCING_MAX_RECORDS_PER_REQUEST=10) class SameVersionTests(CreateAdminMixin, CentralServerMixins, FakeDeviceMixin, LiveServerTestCase): def setUp(self): self.setup_fake_device(name="Central") self.user = self.create_admin() self.org = self.create_organization(owner=self.user) self.zone = self.create_zone(organizations=[self.org]) self._key_factory = KeyFactory() self.settings = { 'CENTRAL_SERVER_HOST':
def create(self, validated_data): model = get_user_model() self._resolve_location(validated_data) validated_data['username'] = validated_data['email'] validated_data['password'] = make_password(validated_data['password']) return model.objects.create(**validated_data)
def update(self, instance, validated_data): self._resolve_location(validated_data) if validated_data.get('password'): validated_data['password'] = make_password( validated_data['password']) return super(UserSerializer, self).update(instance, validated_data)
def register(request): # залогиненых посылаем на глвную if request.user.is_active: return HttpResponseRedirect('/') p_k = rsa_wrapper.get_public_key() if request.method == 'POST': form_data = {} for param in request.POST: if param == 'csrfmiddlewaretoken': continue try: form_data[param] = rsa_wrapper.decrypt_str(request.POST[param]) except Exception as ex: print "Couldn't decode string:%s" % request.POST[param] print ex.message continue form = UserRegistrationForm(form_data) if form.is_valid(): # create new user pas = form_data.pop('password1') form_data['password'] = pas if pas != form_data.pop('password2'): return render_to_response( 'index.html', {'result': u"Не верный пароль"}, context_instance=RequestContext(request), ) pasport_data = form_data.pop(u'pasport_data') try: user, c = PollingUser.objects.get_or_create(**form_data) except IntegrityError: res = "Пользователь уже существует" return render_to_response( 'index.html', {'result': res}, context_instance=RequestContext(request), ) salt = random.randrange(1024) alternative_password = make_password(pas, salt) alt_pas, created = AlternativePassword.objects.get_or_create(user=user) if created: alt_pas.alternative_password = alternative_password alt_pas.save() else: alternative_password = alt_pas.alternative_password done = lambda x: u'Ваш код для голосования %s' % x error = u'Произошла ошибка' res = done(alternative_password) if (alt_pas and user) else error return render_to_response( 'index.html', {'result': res}, context_instance=RequestContext(request), ) data = {'public_key': 'p_k'} form = UserRegistrationForm(data) return render_to_response( 'registration/register.html', {'form': form, 'public_key': json.dumps(p_k)}, context_instance=RequestContext(request), )
def signup(request): """View for Signup.""" # when the user is alread logged in if request.user.pk: return HttpResponseRedirect(reverse("dashboard")) if request.method == "POST": form = forms.SignUpForm(request.POST) if form.is_valid(): data = form.cleaned_data # when the both confirm password and password should match if data["confirm_password"] == data["password"]: # pop the confirm password as it will not be stored in database data.pop("confirm_password") # encrypting the password before storing in database data["password"] = make_password(data["password"], salt="scrapper") # setting the is_active field to false by defautl data["is_active"] = False # creating the user user = User.objects.create(**data) # creating a record in UserDetail table, # with the current registered user id. data1 = {"user_id": user.pk} UserDetail.objects.create(**data1) # generating an unique acitivation key activation_key = generate_activation_key(data["email"]) data2 = {"user_id": user.pk, "activation_key": activation_key} # creating a record in the UserActivation table UserActivation.objects.create(**data2) else: user = None messages.error(request, "Password did not match.") ctx = {"form": form, "title": "Signup", "register": "active", "nav_dashboard": "nav-dashboard"} return render_to_response("usermanager/signup.html", ctx, context_instance=RequestContext(request)) ctx = {"message": ""} if user: # sending activation email try: send_activation_mail(user.username, data["email"], activation_key) # displaying message to the user to activate his accont message = "An acitvation link has been sent to your email id.\ Please activate." # creating the context ctx = { "message_success": message, "title": "Signup", "register": "active", "nav_dashboard": "nav-dashboard", } return render_to_response("usermanager/signup.html", ctx, context_instance=RequestContext(request)) except Exception as e: # displaying error message on email sending failure. messages.error(request, "Email sending failed." + e) # creating the context ctx = {"form": form, "title": "Signup", "register": "active", "nav_dashboard": "nav-dashboard"} return render_to_response("usermanager/signup.html", ctx, context_instance=RequestContext(request)) else: pass elif request.method == "GET": form = forms.SignUpForm() ctx = {"form": form, "title": "Signup", "register": "active", "nav_dashboard": "nav-dashboard"} return render_to_response("usermanager/signup.html", ctx, context_instance=RequestContext(request))
def set_password(self, raw_password): self.password = auth.make_password(raw_password)
def set_unusable_password(self): # Sets a value that will never be a valid hash self.password = auth.make_password(None)
def set_pin(self, raw_pin): self.pin = make_password(raw_pin)
def signup(request): """View for Signup.""" # when the user is alread logged in if request.user.pk: return HttpResponseRedirect(reverse('dashboard')) if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): data = form.cleaned_data # when the both confirm password and password should match if data['confirm_password'] == data['password']: # pop the confirm password as it will not be stored in database data.pop('confirm_password') # encrypting the password before storing in database data['password'] = make_password(data['password'], salt="scrapper") # setting the is_active field to false by defautl data['is_active'] = False # creating the user user = User.objects.create(**data) # creating a record in UserDetail table, # with the current registered user id. data1 = {'user_id': user.pk} UserDetail.objects.create(**data1) # generating an unique acitivation key activation_key = generate_activation_key(data['email']) data2 = {'user_id': user.pk, 'activation_key': activation_key} # creating a record in the UserActivation table UserActivation.objects.create(**data2) else: user = None messages.error(request, 'Password did not match.') ctx = ({ 'form': form, 'title': 'Signup', 'register': 'active', 'nav_dashboard': 'nav-dashboard' }) return render_to_response( 'usermanager/signup.html', ctx, context_instance=RequestContext(request)) ctx = ({'message': ''}) if user: # sending activation email try: send_activation_mail(user.username, data['email'], activation_key) # displaying message to the user to activate his accont message = 'An acitvation link has been sent to your email id.\ Please activate.' # creating the context ctx = ({ 'message_success': message, 'title': 'Signup', 'register': 'active', 'nav_dashboard': 'nav-dashboard' }) return render_to_response( 'usermanager/signup.html', ctx, context_instance=RequestContext(request)) except Exception as e: # displaying error message on email sending failure. messages.error(request, 'Email sending failed.' + e) # creating the context ctx = ({ 'form': form, 'title': 'Signup', 'register': 'active', 'nav_dashboard': 'nav-dashboard' }) return render_to_response( 'usermanager/signup.html', ctx, context_instance=RequestContext(request)) else: pass elif request.method == 'GET': form = forms.SignUpForm() ctx = ({ 'form': form, 'title': 'Signup', 'register': 'active', 'nav_dashboard': 'nav-dashboard' }) return render_to_response('usermanager/signup.html', ctx, context_instance=RequestContext(request))