@@ -48,56 +48,59 @@ module.exports = async function checkAuth(ctx, next) {
48
48
ctx . body = fail ( { message : "code 码无效,请重新登录" , code : 92 } ) ;
49
49
return ;
50
50
}
51
- const { access_token } = await fetch (
52
- `https://github.com/login/oauth/access_token?code=${ code } &client_id=${ clientId } &client_secret=${ secret } ` ,
53
- {
54
- method : "POST" ,
51
+ try {
52
+ const { access_token } = await fetch (
53
+ `https://github.com/login/oauth/access_token?code=${ code } &client_id=${ clientId } &client_secret=${ secret } ` ,
54
+ {
55
+ method : "POST" ,
56
+ headers : {
57
+ Accept : "application/json" ,
58
+ } ,
59
+ }
60
+ ) . then ( ( res ) => res . json ( ) ) ;
61
+
62
+ const user = await fetch ( "https://api.github.com/user" , {
55
63
headers : {
56
64
Accept : "application/json" ,
65
+ Authorization : `token ${ access_token } ` ,
57
66
} ,
58
- }
59
- ) . then ( ( res ) => res . json ( ) ) ;
60
- if ( ! access_token ) return ;
67
+ } ) . then ( ( res ) => res . json ( ) ) ;
61
68
62
- const user = await fetch ( "https://api.github.com/user" , {
63
- headers : {
64
- Accept : "application/json" ,
65
- Authorization : `token ${ access_token } ` ,
66
- } ,
67
- } ) . then ( ( res ) => res . json ( ) ) ;
69
+ // user.login 存在表示登录成功
70
+ if ( user . login ) {
71
+ ctx . cookies . set (
72
+ "token" ,
73
+ encrypt (
74
+ Buffer . from (
75
+ JSON . stringify ( {
76
+ ...user ,
77
+ pay : true ,
78
+ } ) ,
79
+ "utf8"
80
+ )
81
+ ) ,
82
+ {
83
+ httpOnly : false ,
84
+ expires : new Date ( 24 * 60 * 60 * 1000 + Date . now ( ) ) ,
85
+ }
86
+ ) ;
68
87
69
- // user.login 存在表示登录成功
70
- if ( user . login ) {
71
- ctx . cookies . set (
72
- "token" ,
73
- encrypt (
74
- Buffer . from (
75
- JSON . stringify ( {
76
- ...user ,
77
- pay : true ,
78
- } ) ,
79
- "utf8"
80
- )
81
- ) ,
82
- {
83
- httpOnly : false ,
84
- expires : new Date ( 24 * 60 * 60 * 1000 + Date . now ( ) ) ,
88
+ if ( db . find ( ( q ) => q . login === user . login ) ) {
89
+ ctx . session . user = {
90
+ ...user ,
91
+ pay : true ,
92
+ } ;
93
+ } else {
94
+ ctx . session . user = {
95
+ ...user ,
96
+ pay : false ,
97
+ } ;
85
98
}
86
- ) ;
87
-
88
- if ( db . find ( ( q ) => q . login === user . login ) ) {
89
- ctx . session . user = {
90
- ...user ,
91
- pay : true ,
92
- } ;
93
- } else {
94
- ctx . session . user = {
95
- ...user ,
96
- pay : false ,
97
- } ;
98
99
}
99
- }
100
100
101
- await next ( ) ;
101
+ await next ( ) ;
102
+ } catch ( err ) {
103
+ ctx . body = fail ( { message : "登录失败, code 码已失效~" , code : 93 } ) ;
104
+ }
102
105
}
103
106
} ;
0 commit comments