from django.shortcuts import render from .form import UserLoginForm, UserRegisterForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from .models import Profile, Devices from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from .form import ProfileForm import random import datetime import json """ 在此处修改token过期时间,30代表30天过期 """ expiration_date = 30 DEBUG = True def user_login(request): if request.method == 'POST': data = request.POST # 检测是否有登录凭证 if data['token'] != 'token': try: device = Devices.objects.filter(token__exact=data['token']).get() sub_time = (device.last_login_time - datetime.date.today()).total_seconds() / (3600 * 24) # 检查token是否过期 if sub_time < expiration_date: # 更新此user此设备的token # token由设备uid、用户名、当前时间hash得来 device.gen_token() device.save() # 登录 user = device.user login(request, user) response = {'token': device.token} return HttpResponse(json.dumps(response), status=200) # return redirect("chat:index") else: return HttpResponse(status=420) # 已过期的token并且已经被删除 except Devices.DoesNotExist: return HttpResponse(status=420) else: # 检测账号密码是否匹配数据库中的一个用户 # 如果均匹配,则返回此User对象 user = authenticate(username=data['username'], password=data['password']) if user: if data['token'] == 'token': # 新建一个该user的设备 device = create_new_device(user) else: # 此时,客户端带来了过期的旧token,现在需要更新旧的token try: device = Devices.objects.filter(token__exact=data['token']).get() device.gen_token() device.save() except Devices.DoesNotExist: # 新建一个该user的设备 device = create_new_device(user) login(request, user) response = {'token': device.token} return HttpResponse(json.dumps(response), status=200) else: return HttpResponse(status=401) # 用于测试,登录界面 elif request.method == 'GET': if DEBUG: user_login_form = UserLoginForm() context = {'form': user_login_form} return render(request, 'login.html', context) else: # 请求方法错误,请使用POST return HttpResponse(status=400) # 新建一个该user的设备 def create_new_device(user): device = Devices() device.user = user device.device_uid = generate_random_str(100) device.gen_token() device.save() return device def generate_random_str(random_length=16): """ 生成一个指定长度的随机字符串 """ random_str = '' base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789' length = len(base_str) - 1 for i in range(random_length): random_str += base_str[random.randint(0, length)] return random_str def user_logout(request): logout(request) return HttpResponse(status=200) def user_register(request): if request.method == 'POST': user_register_form = UserRegisterForm(data=request.POST) if user_register_form.is_valid(): # 新建一个user,但是不提交 new_user = user_register_form.save(commit=False) # 设置密码 new_user.set_password(user_register_form.cleaned_data['password']) # 保存 new_user.save() return HttpResponse(status=200) else: return HttpResponse(status=400) # 用于测试 elif request.method == 'GET': if DEBUG: user_register_form = UserRegisterForm() context = {'form': user_register_form} return render(request, 'register.html', context) else: return HttpResponse(status=400) @login_required(login_url='/account/login/') def profile_edit(request, r_username): user = User.objects.get(username=r_username) profile = Profile.objects.get(user__exact=user) if request.method == 'POST': # 判断此用户是否正在修改自身账号信息 if request.user != user: return HttpResponse(status=403) profile_form = ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): # 填入信息 profile_cd = profile_form.cleaned_data profile.phone = profile_cd['phone'] profile.bio = profile_cd['bio'] if 'avatar' in request.FILES: profile.avatar = profile_cd["avatar"] profile.save() return HttpResponse(status=200) else: return HttpResponse(status=400) # 用于测试 elif request.method == 'GET': if DEBUG: profile_form = ProfileForm() context = {'profile_form': profile_form, 'profile': profile, 'user': user} return render(request, 'edit.html', context) else: return HttpResponse(status=400) @login_required(login_url='/account/login/') def profile_detail(request, r_username): user = User.objects.get(username=r_username) profile = Profile.objects.get(user__exact=user) if request.method == 'POST': response = {} if profile.phone: response['phone'] = profile.phone else: response['phone'] = '' if profile.bio: response['bio'] = profile.bio else: response['bio'] = '' if profile.avatar: response['avatar'] = profile.avatar.url else: response['avatar'] = '' return HttpResponse(json.dumps(response), status=200) # 用于测试 elif request.method == 'GET': if DEBUG: profile_form = ProfileForm() context = {'profile_form': profile_form, 'profile': profile, 'user': user} return render(request, 'edit.html', context) else: return HttpResponse(status=400)