123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- from django.shortcuts import render, redirect
- 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
- def user_login(request):
- if request.method == 'POST':
- user_login_form = UserLoginForm(request.POST)
- if user_login_form.is_valid():
- # 清洗出合法的数据
- data = user_login_form.cleaned_data
- # 检测是否有登录凭证
- if data['token'] != 'token':
- try:
- device = Devices.objects.filter(token__exact=data['token']).get()
- sub_time = (device.last_login_time - datetime.date).total_seconds() / (3600 * 24)
- # 检查token是否过期
- if sub_time < expiration_date:
- # 更新此user此设备的token
- # token由设备uid、用户名、当前时间hash得来
- device.token = hash(
- device.device_uid + device.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
- device.save()
- # 登录
- user = device.user
- login(request, user)
- response = ['login successfully', device.token]
- return HttpResponse(json.dumps(response))
- # return redirect("chat:index")
- else:
- response = ['token time out']
- return HttpResponse(json.dumps(response))
- # 已过期的token并且已经被删除
- except Devices.DoesNotExist:
- response = ['detected new device, please login']
- return HttpResponse(json.dumps(response))
- 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.token = hash(
- device.device_uid + device.user.username + datetime.datetime.now().strftime(
- "%Y%m%d%H%M%S"))
- device.save()
- except Devices.DoesNotExist:
- # 新建一个该user的设备
- device = create_new_device(user)
- login(request, user)
- response = ['login successfully', device.token]
- return HttpResponse(json.dumps(response))
- else:
- response = ['wrong account or password']
- return HttpResponse(json.dumps(response))
- else:
- response = ['illegal input']
- return HttpResponse(json.dumps(response))
- # 用于测试,登录界面
- # elif request.method == 'GET':
- # user_login_form = UserLoginForm()
- # context = {'form': user_login_form}
- # return render(request, 'login.html', context)
- else:
- # 请求方法错误,请使用POST
- response = ['illegal method, please use post']
- return HttpResponse(json.dumps(response))
- # 新建一个该user的设备
- def create_new_device(user):
- device = Devices()
- device.user = user
- device.device_uid = generate_random_str(10)
- device.token = hash(
- device.device_uid + device.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
- 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)
- response = ['logout successfully']
- return HttpResponse(json.dumps(response))
- 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()
- response = ['reg successfully']
- return HttpResponse(json.dumps(response))
- else:
- response = ['illegal input']
- return HttpResponse(json.dumps(response))
- # 用于测试
- # elif request.method == 'GET':
- # user_register_form = UserRegisterForm()
- # context = {'form': user_register_form}
- # return render(request, 'register.html', context)
- else:
- response = ['illegal method, please use post']
- return HttpResponse(json.dumps(response))
- @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':
- # 判断此用户是否正在修改自身账号信息
- if request.user != user:
- response = ['You do not have permission to do this']
- return HttpResponse(json.dumps(response))
- 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']
- profile.avatar = profile_cd["avatar"]
- profile.save()
- response = ['edit successfully']
- return HttpResponse(json.dumps(response))
- else:
- response = ['illegal input']
- return HttpResponse(json.dumps(response))
- # 用于测试
- # elif request.method == 'GET':
- # profile_form = ProfileForm()
- # context = {'profile_form': profile_form, 'profile': profile, 'user': user}
- # return render(request, 'edit.html', context)
- else:
- response = ['illegal method, please use post']
- return HttpResponse(json.dumps(response))
|