def register_mobile(request): data={} if request.method=='POST': logger.debug(str(request.POST)) try: mobile=request.POST.get('mobile') password=request.POST.get('password') confirmpass=request.POST.get('confirmpass') own_imsi=request.POST.get('imsi') nick_name=request.POST.get('nick_name') except KeyError: data['status']=14 data['error']='missing items' return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json') if password!=confirmpass: data['status']=10 data['error']='password not correct' return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json') # password=make_password(password) user_name=mobile logger.debug("[Register]:"+str(user_name)+" / "+str(password)) try: check_user = User.objects.get(username=user_name) data['status']=16 data['error']='mobile already used' return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json') except ObjectDoesNotExist: try: check_user_info = UserInfo.objects.get(imsi=own_imsi) data['status']=22 data['error']='imsi already used' return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json') except ObjectDoesNotExist: user=User(username=user_name,password=password,is_staff=False,is_active=True,is_superuser=False) user.save() user=User.objects.get(username=user_name) userinfo=UserInfo(user=user) userinfo.imsi = own_imsi userinfo.nickname = nick_name userinfo.save() data['status']=0 return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json') data['status']=404 return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json')
def register(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response({'error': 'Username has already been taken'}, status=HTTP_400_BAD_REQUEST) user = User.objects.create_user(username=username, password=password) userInfo = UserInfo(username=username) userInfo.save() token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK)
def create(request): if request.method == 'POST': body_data = request.body myuser = request.myuser if myuser.user_permission != 1: return JsonResponse(code[10410]) data = judge_data_complate(body_data) if not data: return JsonResponse(code[10001]) name = data.get('username') f_passwd_f = str(data.get('f_passwd')) s_passwd_s = str(data.get('s_passwd')) try: f_passwd = decode_passwd(f_passwd_f) s_passwd = decode_passwd(s_passwd_s) except Exception as e: return JsonResponse(code[10409]) if f_passwd != s_passwd: return JsonResponse(code[10003]) try: flag = UserInfo().create_user(data, s_passwd) if not flag: return JsonResponse(code[10002]) except Exception as e: return JsonResponse(code[10401]) # 签发token action_info = f'创建用户: [{name}]' write_sys_log(action_info, myuser) res_data = code[200] res_data['token'] = make_token(name).decode() return JsonResponse(res_data) else: return JsonResponse(code[60001])
def get_all_user_info(request): if request.method == "GET": result = UserInfo().get_all_user() res_data = code[200] res_data['data'] = result['data'] return JsonResponse(res_data) else: return JsonResponse(code[60001])
def register_handle(request): """注册判断""" user_table = request.POST user_name = user_table.get('user_name') pwd = user_table.get('pwd') cpwd = user_table.get('cpwd') email = user_table.get('email') allow = user_table.get('allow') # user_name、pwd还需加验证,注册失败,未勾选同意协议 给出对应的提示 user_name_count = UserInfo.objects.filter(uname=user_name).count() email_count = UserInfo.objects.filter(uemail=email).count() if user_name_count>=1 or pwd!=cpwd or email_count>=1 or email=='' or user_name=='' or pwd=='' or cpwd=='' or allow=='': # context = {'title':'注册','error_name':0} return redirect('/user/register/') # 加密 s1 = sha1() s1.update(pwd.encode("utf-8")) pwd_sha1 = s1.hexdigest() #写入数据库 user = UserInfo() user.uname = user_name user.upwd = pwd_sha1 user.uemail = email user.save() return redirect('/user/login/')
def create(self, validated_data): with transaction.atomic(): instance = UserInfo() instance.role_id = validated_data.get("role_id", '') instance.username = validated_data.get("username", '') password = validated_data.get("password") instance.password = make_password(password) instance.save() return instance
def authenticate(self, request): uid = request.session.get(SESSION_ID) if not uid: raise exceptions.AuthenticationFailed('用户未登录') user_dict = cache.get(create_key(CACHE_USER, uid)) # 缓存中不存在从数据库中取值,并更新到缓存 if not user_dict: user = UserInfo.objects.filter(id=uid).first() if user: # json序列化,并存入缓存 user_dict = UserInfoSerializer(user, many=False).data cache.set(create_key(CACHE_USER, uid), user_dict, timeout=None) if not user_dict: raise exceptions.AuthenticationFailed('用户未登录') user = UserInfo() user.__dict__ = user_dict # 在rest framework内部会将这两个字段赋值给request,以供后续操作使用 return user, None
def get(self, request): try: myuser = request.myuser user_id = request.GET.get('user_id') if not user_id: return JsonResponse(code[10004]) flag, username = UserInfo().delete_user_info(user_id) if not flag: return JsonResponse(code[10402]) action_info = f'删除用户: [{username}]' write_sys_log(action_info, myuser) return JsonResponse(code[200]) except Exception as e: print(e) return JsonResponse(code[10402])
def post(self, request, *args, **kwargs): try: password = self.request.data.get("password") username = self.request.data.get("username") is_active = self.request.data.get("is_active") account = self.request.data.get("account") telephone = self.request.data.get("telephone") gender = self.request.data.get("gender") userNo = self.request.data.get("userNo") address = self.request.data.get("address") detail = self.request.data.get("detail") avatar = self.request.data.get("avatar") user = User(username=username, password=make_password(password), is_active=is_active) user.save() userInfo = UserInfo(account=account, telephone=telephone, gender=gender, userNo=userNo, address=address, detail=detail, avatar=avatar) userInfo.user = user userInfo.save() except: return Response(data={ "code": 400, "message": "新增用户失败!" }, status=status.HTTP_400_BAD_REQUEST) return Response(data={ "code": 200, "message": "新增用户成功" }, status=status.HTTP_201_CREATED)
def register(request): myRes = MyResponse() username = request.POST.get("username") email = request.POST.get("email") pwd = request.POST.get("pwd") pwd_ok = request.POST.get("pwd_ok") try: if len(username) < 6 or len(username) > 64: return myRes.to_json_msg("用户名长度应在6-64之间") if not re.match(r"^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email): # 返回错误信息 return myRes.to_json_msg("邮箱格式不正确") elif pwd != pwd_ok: return myRes.to_json_msg("密码不一致,请重新输入") user = UserInfo.objects.filter(username=username).first() if user: return myRes.to_json_msg("用户名已存在") user = UserInfo.objects.filter(email=email).first() if user: return myRes.to_json_msg("邮箱已存在") pwd = make_password(pwd, None, 'pbkdf2_sha256') user = UserInfo(username=username, pwd=pwd, email=email) user.save() myRes.status = ResState.HTTP_SUCCESS # 将注册激活token发送给用户激活 token = TokenHandler().encrypt(str(user.id)) user_id = TokenHandler().decrypt(token) logger.info("user_id is {0}".format(user_id)) # send_register_email(username,token,email) tasks.send_register_email.delay(username, token, email) except Exception as ex: logger.error("Register error by {0}".format(ex)) myRes.msg = str(ex) return myRes.to_json()
def get(self, request, format=None): if User.objects.all().count() <= 0: newuser = User(password='******', nickname='小朋友', email='*****@*****.**', signup_type='email', lastlogin=timezone.now(), signup_time=timezone.now()) newuser.save() userinfo = UserInfo(user=newuser, registerinfo="10") userinfo.save() data = [ { 'text': '第一条开心', 'type_raw': "happy" }, { 'text': '第一条生气', 'type_raw': "angry" }, { 'text': '第一条讨厌', 'type_raw': "disgust" }, { 'text': '第一条悲伤', 'type_raw': "sad" }, ] for d in data: editor = Editor(content=d['text'], text=d['text']) editor.save() t = Thought(type_raw=d['type_raw'], rich_text=editor) t.save() return Response('init') return Response('already init')
def post(self, request): data = json.loads(request.body) try: # hashing password hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()) # if userid already exists in the db if UserInfo.objects.filter(user_id=data['user_id']).exists(): return JsonResponse({'message': 'USER_ID_ALREADY_EXISTS'}, status=401) # validating the password try: validate_password(data['password']) except ValidationError: return JsonResponse({'message': 'INVALID_PASSWORD'}, status=401) # if nickname already exists in the db if UserInfo.objects.filter(nickname=data['nickname']).exists(): return JsonResponse({'message': 'NICKNAME_ALREADY_EXISTS'}, status=401) # validating email address try: validate_email(data['email']) except: return JsonResponse({'message': 'INVALID_EMAIL'}) # if email already exists in the db if UserInfo.objects.filter(email=data['email']).exists(): return JsonResponse({'message': 'EMAIL_ALREADY_EXISTS'}) # All necessary info validated, save into DB UserInfo(user_id=data['user_id'], password=hashed_password.decode('utf-8'), nickname=data['nickname'], email=data['email'], name=data['name'], phone_number=data['phone_number'], address=data['address']).save() return JsonResponse({'message': 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'message': 'INVALID_KEY'}, status=401)
def register(request): username = request.POST.get('username') password = request.POST.get('password') users = UserInfo.objects.all() for user in users: if username == user.username: return JsonResponse({'res': 0}) newuser = UserInfo() newuser.username = username newuser.password = password newuser.save() return JsonResponse({'res': 1})
def post(self, request): myuser = request.myuser body_data = request.body data = judge_data_complate(body_data) if not data: return JsonResponse(code[10001]) try: flag, username = UserInfo().update_user_info(data) if not flag: return JsonResponse(code[10004]) action_info = f'修改用户: [{username}]' write_sys_log(action_info, myuser) return JsonResponse(code[200]) except Exception as e: print(e) res_data = code[10403] res_data['info'] = e return JsonResponse(code[10403])
def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): print("valid") form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') mnumber = form.cleaned_data.get('mobile_no') print(mnumber) user = authenticate(username=username, password=raw_password) login(request, user) UserInfo(user_id=user.id, email=username, mobile_no=mnumber).save() return redirect('post_list') else: if request.user.is_authenticated: return redirect('post_list') form = SignUpForm() return render(request, 'signup.html', {'form': form})
def register(request): username = request.POST.get("username") passwd = request.POST.get("password") confirm_passwd = request.POST.get("confirm_password") email= request.POST.get("email") if passwd==confirm_passwd and len(passwd) >= 8: user = UserInfo() passwd = gen_sec_passwd(passwd) confirm_passwd = gen_sec_passwd(confirm_passwd) user.username = username user.passwd = passwd user.confirm_passwd = confirm_passwd user.email = email user.save() print("加密后的密码是:%s"%passwd) return HttpResponse("注册成功") print("*"*50) print(username, passwd, confirm_passwd, email) return HttpResponse("密码输入不符合规范")
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = request.POST.get('email', '') if UserInfo.objects.filter(email=email): return render(request, 'register.html', { 'register_form': register_form, 'message': '用户已经存在!' }) pass_word = request.POST.get('password', '') user_profile = UserInfo() user_profile.username = email user_profile.email = email user_profile.is_active = False user_profile.password = make_password(pass_word) user_profile.save() # 发送邮箱,这里会生成一个16位随机数并存储到EmailVerify中 send_register_email(email, 'register') return HttpResponseRedirect(reverse('user:login')) else: return render(request, 'register.html', {'register_form': register_form})
def get_user_info(request): """ 修改用户 或 key基本信息 :param request: 根据key_word 判断修改的为用户信息 还是key信息 :return: """ if request.method == "GET": page = request.GET.get('page') max_count = request.GET.get('max_count') search_word = request.GET.get('search_word') try: data_dic = UserInfo().query_user_info(page, max_count, search_word) res_data = code[200] res_data['data'] = data_dic['data'] res_data['total'] = data_dic['total_page'] except Exception as e: print(e) err_data = code[60003] err_data['info'] = str(e) return JsonResponse(err_data) return JsonResponse(res_data) else: return JsonResponse(code[60001])
def boss_create(request): mobile = request.POST.get('mobile') password = request.POST.get('password') confirmpass = request.POST.get('confirmpass') imsi = request.POST.get('imsi') nick_name = request.POST.get('nick_name') lat = request.POST.get('lat') lng = request.POST.get('lng') desc = request.POST.get('desc') life = request.POST.get('life') reward = request.POST.get('reward') user=User(username=mobile,password=password,is_staff=False,is_active=True,is_superuser=False) user.save() boss = UserInfo(user=user,lat=lat, lng=lng, desc=desc, life_value=life, reward=reward) boss.imsi = own_imsi boss.nickname = nick_name boss.category = 3 boss.save()
def post(self, request): '''登陆/注册?''' reType = request.POST.get('type') if reType == 'login': '''ajax登陆检查''' # 获取数据 username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if settings.DEBUG == True: print('{username}--登陆'.format(username=username)) try: print('{username}--认证'.format(username=user.username)) except: pass # 校验数据 if not all([username, password]): return JsonResponse({'check': '2'}) # 业务处理 # elif username == 'Louis' and password == '201314abc': elif user is not None: if user.is_active: # 用户已激活 next_url = request.POST.get('next', reverse('main:home')) print(next_url) # 设置session,标记为登陆 login(request, user) return JsonResponse({ 'check': '1', 'next': next_url }) # 登陆成功 else: #用户未激活 send_email(user.id, user.email, username) errmsg = '用户{user}未激活,已重新发送邮件'.format(user=username) return JsonResponse({'check': '3', 'errmsg': errmsg}) else: # 用户名或密码错误 return JsonResponse({'check': '0'}) elif reType == 'register': '''ajax注册处理''' # 接收数据 username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') # 进行校验 if not all([username, password, email]): # 数据不完整 return JsonResponse({'statusCode': 2}) if not re.match( r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email): # 邮箱形式不对 return JsonResponse({'statusCode': 3}) # 进行业务处理:注册 # 查找用户名是否重复 try: user = User.objects.get(username=username) except User.DoesNotExist: user = "" try: emails = User.objects.get(email=email) except User.DoesNotExist: emails = "" if user: return JsonResponse({'statusCode': 0}) elif emails: return JsonResponse({'statusCode': 4}) elif user == "" and emails == "": user = User.objects.create_user(username, email, password) user.is_active = 0 info = UserInfo() info.user = user info.nickname = username user.save() info.save() #发送激活邮件,包含激活链接:http://nchu-UTP/active/[加盐id] #if send_register_active_email(user.id, email, username): #celery异步处理 if send_email(user.id, email, username): # 返回应答 return JsonResponse({'statusCode': 1}) else: return JsonResponse({'statusCode': 5})