Skip to content

Commit

Permalink
fix: added comments for clarification
Browse files Browse the repository at this point in the history
  • Loading branch information
SamCaliman committed Jul 4, 2024
1 parent 514cb86 commit 22a4a1e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 23 deletions.
46 changes: 29 additions & 17 deletions api/src/routes/github.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { createRouter, HTTPStatus, Result, successfulAuthentication } from 'aeria'
import { ACError, createRouter, Result, successfulAuthentication } from 'aeria'

export const githubRouter = createRouter()

const GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'

const GITHUB_USER_URL = 'https://api.github.com/user'

//exchange github temporary code for an Access Token so we can access user data
async function exchangeCodeForAccessToken(code: string) {
if(!process.env.GITHUB_CLIENT_ID || !process.env.GITHUB_CLIENT_SECRET){
throw new Error('INVALID ENV FILES')
Expand All @@ -30,7 +31,7 @@ async function exchangeCodeForAccessToken(code: string) {
const responseObject = await githubResponse.json()
return responseObject
}

//get github user data with Access Token
async function fetchUser(token: string) {
const userResponse = await fetch(GITHUB_USER_URL,{
method: 'GET',
Expand All @@ -43,29 +44,40 @@ async function fetchUser(token: string) {
}

githubRouter.POST('/githubAuth', async(context)=>{
const gitTempToken = await exchangeCodeForAccessToken(context.request.payload.code)
const gitTempUser = await fetchUser(gitTempToken.access_token)
const gitTempToken = await exchangeCodeForAccessToken(context.request.payload.code) //swap code for access token
const gitTempUser = await fetchUser(gitTempToken.access_token) // get github user data

//checks if there's an user with a github account on the database.
const { error: userError ,result: user } = await context.collections.user.functions.get({
filters: {
github_id: gitTempUser.id.toString(),
},
})

if(userError){
const { error: userInsertError, result: userInsertResult } = await context.collections.user.functions.insert({
what: {
name: gitTempUser.login,
active: true,
github_id: gitTempUser.id.toString(),
roles: ['root'],
email: `${gitTempUser.login}@user.github.com`,
},
})
if (userInsertError){
return Result.error(userInsertError)
//Check what user error returns
switch(userError.code){
case ACError.ResourceNotFound:{
//if there's no user on database, create one.
const { error: userInsertError, result: userInsertResult } = await context.collections.user.functions.insert({
what: {
name: gitTempUser.login,
active: true,
github_id: gitTempUser.id.toString(),
roles: ['root'],
email: `${gitTempUser.login}@user.github.com`,
},
})
if (userInsertError){
return Result.error(userInsertError)
}
//Authenticate if successful, and return result to web
return Result.result(await successfulAuthentication(userInsertResult._id, context))
}
default:
return Result.error(userError)
}
return Result.result(await successfulAuthentication(userInsertResult._id, context))
}
//if user already exists in database just authenticate and return result to web
return Result.result(await successfulAuthentication(user._id, context))
})
5 changes: 3 additions & 2 deletions web/src/pages/githubAuth.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const CLIENT_ID = import.meta.env.VITE_GITHUB_CLIENT_ID
const GITHUB_URL = 'https://github.com/login/oauth/authorize'
// Redirect User to github OAuth page, passing the client id as an paramenter
async function githubAuth() {
const params = {
response_type: 'code',
Expand Down Expand Up @@ -39,8 +40,8 @@ async function githubAuth() {
tw-text-white
"
>
fazer login com github
<aeria-button @click="githubAuth()">clique</aeria-button>
Login With Github
<aeria-button @click="githubAuth()">Login</aeria-button>
</div>
</section>

Expand Down
11 changes: 7 additions & 4 deletions web/src/pages/redirect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@ type SuccessfulAuthentication = {
}
onMounted(async ()=>{
//get github temporary code when returning from authorization page
const gitTempCode = router.currentRoute.value.query.code
//if github code exists call API authentication route
if(gitTempCode){
const {error,result}: Result.Either<EndpointError, SuccessfulAuthentication>= await aeria.github.githubAuth.POST({
code: gitTempCode
}) as any
}) as any //this casting 'as any' is necessary only because there's no contract on route
if(error){
//if authentication fails, go back to login page
router.push('/githubAuth')
//window.open('http://localhost:8080/githubAuth', '_self')
return
}
//if authentication succeeds, login returned user and go to dashboard
userStore.$actions.setCurrentUser(result)
router.push('/dashboard')
//window.open('http://localhost:8080/dashboard', '_self')
}
})
Expand Down Expand Up @@ -53,7 +56,7 @@ onMounted(async ()=>{
tw-text-white
"
>
Aguarde enquanto verificamos seu login
Wait while we verify your login
</div>
</section>

Expand Down

0 comments on commit 22a4a1e

Please sign in to comment.