@@ -43,6 +43,8 @@ import { can } from "../helpers/authorization";
4343import { authenticator } from "otplib" ;
4444import ClientOAuth2 from "client-oauth2" ;
4545import { GITHUB_CLIENT_ID , GITHUB_CLIENT_SECRET } from "../config" ;
46+ import axios from "axios" ;
47+ import { GitHubEmail } from "../interfaces/oauth" ;
4648
4749export const validateRefreshToken = async ( token : string , locals : Locals ) => {
4850 const data = < User > await verifyToken ( token , Tokens . REFRESH ) ;
@@ -199,22 +201,44 @@ export const approveLocation = async (token: string, locals: Locals) => {
199201 ) ;
200202} ;
201203
202- // OAuth2 clients
204+ /*
205+ OAuth clients
206+ */
207+
203208export const github = new ClientOAuth2 ( {
204209 clientId : GITHUB_CLIENT_ID ,
205210 clientSecret : GITHUB_CLIENT_SECRET ,
206211 accessTokenUri : "https://github.com/login/oauth/access_token" ,
207212 authorizationUri : "https://github.com/login/oauth/authorize" ,
208213 redirectUri : "https://staart-demo.o15y.com/auth/callback/github" ,
209- scopes : [ "user" ]
214+ scopes : [ "user:email " ]
210215} ) ;
211- export const oauthCallback = async ( service : ClientOAuth2 , url : string ) => {
212- const response = await service . code . getToken ( url ) ;
213- console . log ( "Got" , response . data ) ;
214- return { hello : "hello world" , data : response . data } ;
215- // const email = response.data.email;
216- // if (!email) throw new Error(ErrorCode.USER_NOT_FOUND);
217- // const user = await getUserByEmail(email);
218- // if (!user.id) throw new Error(ErrorCode.USER_NOT_FOUND);
219- // return await getLoginResponse(user, EventType.AUTH_LOGIN, "github", locals);
216+ export const githubCallback = async ( url : string , locals : Locals ) => {
217+ const response = await github . code . getToken ( url ) ;
218+ const emails = ( ( await axios . get ( "https://api.github.com/user/emails" , {
219+ headers : {
220+ Authorization : `token ${ response . accessToken } `
221+ }
222+ } ) ) . data as GitHubEmail [ ] ) . filter ( emails => ( emails . verified = true ) ) ;
223+ for await ( const email of emails ) {
224+ try {
225+ const user = await getUserByEmail ( email . email ) ;
226+ return await getLoginResponse (
227+ user ,
228+ EventType . AUTH_LOGIN_OAUTH ,
229+ "github" ,
230+ locals
231+ ) ;
232+ } catch ( error ) { }
233+ }
234+ throw new Error ( ErrorCode . OAUTH_NO_EMAIL ) ;
220235} ;
236+
237+ export const microsoft = new ClientOAuth2 ( {
238+ clientId : GITHUB_CLIENT_ID ,
239+ clientSecret : GITHUB_CLIENT_SECRET ,
240+ accessTokenUri : "https://login.microsoftonline.com/common/oauth2/v2.0/token" ,
241+ authorizationUri : "https://www.facebook.com/v3.3/dialog/oauth" ,
242+ redirectUri : "https://staart-demo.o15y.com/auth/callback/microsoft" ,
243+ scopes : [ "email" ]
244+ } ) ;
0 commit comments