Django框架课-acapp端一键登录

Django框架课-acapp端一键登录

image

参考链接:AcApp端AcWing一键登录

补充:自己改了js,用户在acapp中并不知道要重新更新应用怎么办?

在acapp应用编辑页面,修改game.js的名字,比如改成game-v1.js这样用户再次打开acapp应用就会强制更新js资源(当然,服务端acapp/static/js下的game.js也要改成响应的名字game-v1.js)

acapp授权登录

首先实现两个后端函数,copy一下上次web端的代码,基础上修改即可

修改(~/acapp/game/views/settings/acwinglogin/acapp/)apply_code.py:

from django.http import JsonResponse
from urllib.parse import quote
from random import randint
from django.core.cache import cache

def get_state():
    res = ""
    for i in range(8):
        res += str(randint(0,9))
    return res

def apply_code(request):
    appid = "4346"
    redirect_uri = quote("https://app4346.acapp.acwing.com.cn/settings/acwinglogin/acapp/receive_code/")
    scope = "userinfo"
    state = get_state()

    cache.set(state,True,7200) # 状态码有效期2h


    return JsonResponse({
        'result':"success",
        'appid': appid,
        'redirect_uri': redirect_uri,
        'scope': scope,
        'state': state,
    })

修改路由:

from django.urls import path
from game.views.settings.acwinglogin.web.apply_code import apply_code as web_apply_code
from game.views.settings.acwinglogin.web.receive_code import receive_code as web_receive_code
from game.views.settings.acwinglogin.acapp.apply_code import apply_code as acapp_apply_code
from game.views.settings.acwinglogin.acapp.receive_code import receive_code as acapp_receive_code

urlpatterns = [
    path("web/apply_code/",web_apply_code,name="settings_acwinglogin_web_apply_code"),
    path("web/receive_code/",web_receive_code,name="settings_acwinglogin_web_receive_code"),
    path("acapp/apply_code/",acapp_apply_code,name="settings_acwinglogin_acapp_apply_code"),
    path("acapp/receive_code/",acapp_receive_code,name="settings_acwinglogin_acapp_receive_code"),
]

然后写前端js
修改settings/zbases.js:

start() {
        if(this.platform === "ACAPP") {
            this.getinfo_acapp();
        } else {
            this.getinfo_web();
            this.add_listening_events();
        }
    }

acapp_login(appid, redirect_uri, scope, state) {
        let outer = this;

        this.root.AcWingOS.api.oauth2.authorize(appid, redirect_uri, scope, state, function(resp){
            console.log(resp);
            if(resp.result === "success") {
                outer.username = resp.username;
                outer.photo = resp.photo;
                outer.hide();
                outer.root.menu.show();
            }
        });
    }

    getinfo_acapp() { // acapp端getinfo
        let outer = this;

        $.ajax({
            url: "https://app4346.acapp.acwing.com.cn/settings/acwinglogin/acapp/apply_code/",
            type: "GET",
            success: function(resp) {
                if (resp.result === "success") {
                    outer.acapp_login(resp.appid, resp.redirect_uri, resp.scope, resp.state);
                }
            }
        });
    }

然后写获得授权码的函数(redirect_uri的路由的处理函数)

~/acapp/game/views/settings/acwinglogin/acapp/)receive_code.py:

from django.http import JsonResponse
from django.core.cache import cache
import requests
from django.contrib.auth.models import User
from game.models.player.player import Player
from random import randint


def receive_code(request):
    data = request.GET

    if "errcode" in data:
        return JsonResponse({
            'result': "apply failed",
            'errcode': data['errcode'],
            'errmsg': data['errmsg'],
        })

    code = data.get('code')
    state = data.get('state')


    if not cache.has_key(state):
        return JsonResponse({
            'result': "state not exist"
        })

    cache.delete(state)

    apply_access_token_url = "https://www.acwing.com/third_party/api/oauth2/access_token/"
    params = {
        'appid': "4346",
        'secret': "4a46fd40e56445bbb33b4489443fb23c",
        'code': code
    }

    access_token_res = requests.get(apply_access_token_url,params=params).json()
    access_token = access_token_res['access_token']
    openid = access_token_res['openid']


    players = Player.objects.filter(openid=openid)
    if players.exists(): # 如果该用户信息已经存在了,就无需重新获取信息,直接登录即可
        player = players[0]
        return JsonResponse({
            'result': "success",
            'username': player.user.username,
            'photo': player.photo,
        })

    get_userinfo_url = "https://www.acwing.com/third_party/api/meta/identity/getinfo/"
    params = {
        "access_token": access_token,
        "openid": openid
    }
    userinfo_res = requests.get(get_userinfo_url,params=params).json()
    username = userinfo_res['username']
    photo = userinfo_res['photo']

    while User.objects.filter(username=username).exists(): # 找到一个新用户名
        username += str(randint(0,9))

    user = User.objects.create(username=username)
    player = Player.objects.create(user=user,photo=photo,openid=openid)

    return JsonResponse({
        'result': "success",
        'username': player.user.username,
        'photo': player.photo,
    })

重新打包,重启服务,打开acapp可以发现需要授权登录

posted @ 2023-03-03 17:06  r涤生  阅读(48)  评论(1编辑  收藏  举报