Skip to content

Commit

Permalink
chore: refactored api in components
Browse files Browse the repository at this point in the history
  • Loading branch information
SamCaliman committed Jul 27, 2024
1 parent 4bb388e commit a068768
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 188 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,32 @@ You may sign in into your application visiting `http://localhost:8080/user/signi
## for the Env files

### api
- github
```
GITHUB_CLIENT_ID = your_client_id
GITHUB_CLIENT_SECRET = your_client_secret
GITHUB_TOKEN_URL=https://github.com/login/oauth/access_token
GITHUB_USER_URL=https://api.github.com/user
GITHUB_REDIRECT_URI=http://localhost:8080/redirectGit
```
- twitch
```
TWITCH_CLIENT_ID = your_client_id
TWITCH_CLIENT_SECRET = your_client_secret
TWITCH_TOKEN_URL= https://id.twitch.tv/oauth2/token
TWITCH_USER_URL=https://api.twitch.tv/helix/users
TWITCH_REDIRECT_URI=http://localhost:8080/redirectTwitch
```
- google
```
GOOGLE_CLIENT_ID = your_client_id
GOOGLE_CLIENT_SECRET = your_client_secret
GOOGLE_TOKEN_URL=https://accounts.google.com/o/oauth2/token
GOOGLE_USER_URL=https://www.googleapis.com/oauth2/v3/userinfo
GOOGLE_REDIRECT_URI=http://localhost:8080/redirectGoogle
```

### web
Expand Down
11 changes: 10 additions & 1 deletion api/@types/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,19 @@ declare global {
| 'STORAGE_TEMP_PATH'
| 'GITHUB_CLIENT_ID'
| 'GITHUB_CLIENT_SECRET'
| 'GITHUB_TOKEN_URL'
| 'GITHUB_USER_URL'
| 'GITHUB_REDIRECT_URI'
| 'TWITCH_CLIENT_ID'
| 'TWITCH_CLIENT_SECRET'
| 'TWITCH_TOKEN_URL'
| 'TWITCH_USER_URL'
| 'TWITCH_REDIRECT_URI'
| 'GOOGLE_CLIENT_ID'
| 'GOOGLE_CLIENT_SECRET',
| 'GOOGLE_CLIENT_SECRET'
| 'GOOGLE_TOKEN_URL'
| 'GOOGLE_USER_URL'
| 'GOOGLE_REDIRECT_URI',
string
> {}
}
Expand Down
40 changes: 40 additions & 0 deletions api/src/oauth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const exchangeCodeForAccessToken = async(code: string, clientId: string, clientSecret: string, tokenUrl:string, redirectUri:string) => {
const body = {
code: code,
grant_type: 'authorization_code',
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri
}
const tokenResponse = await fetch(tokenUrl,{
method: 'POST',
body: new URLSearchParams(body),
headers: {
Accept: 'application/json',
},
})
const responseObject = await tokenResponse.json()
return responseObject
}
//get user data with Access Token

const fetchUser = async(token: string, userUrl: string, clientId:string, accept:string) => {
const userResponse = await fetch(userUrl,{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
"Accept": accept,
"Client-ID": clientId
},
})
const response = await userResponse.json()
if(response.data){
return response.data[0]
}
return response
}

export const OAuth = {
exchangeCodeForAccessToken,
fetchUser
}
76 changes: 76 additions & 0 deletions api/src/routes/implementations/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { ACError, type RouteContext, Result, successfulAuthentication } from 'aeria'
import {OAuth} from '../../oauth.js'

export const github = async(context: RouteContext)=>{
if(
!process.env.GITHUB_CLIENT_ID
||
!process.env.GITHUB_CLIENT_SECRET
||
!process.env.GITHUB_USER_URL
||
!process.env.GITHUB_TOKEN_URL
||
!process.env.GITHUB_REDIRECT_URI
){
throw new Error('INVALID ENV FILES')
}

const CLIENT_ID = process.env.GITHUB_CLIENT_ID
const CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET
const USER_URL = process.env.GITHUB_USER_URL
const TOKEN_URL = process.env.GITHUB_TOKEN_URL
const REDIRECT_URI = process.env.GITHUB_REDIRECT_URI

const gitTempToken = await OAuth.exchangeCodeForAccessToken(
context.request.payload.code,
CLIENT_ID,
CLIENT_SECRET,
TOKEN_URL,
REDIRECT_URI
) //swap code for access token

const gitTempUser = await OAuth.fetchUser(
gitTempToken.access_token,
USER_URL,
CLIENT_ID,
"Accept: application/vnd.github+json"
) // 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){
//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.template.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)
}
}
//if user already exists in database just authenticate and return result to web
return Result.result(await successfulAuthentication(user._id, context))
}



73 changes: 73 additions & 0 deletions api/src/routes/implementations/google.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { ACError, type RouteContext, Result, successfulAuthentication } from 'aeria'
import {OAuth} from '../../oauth.js'

export const google = async(context: RouteContext)=>{
if(
!process.env.GOOGLE_CLIENT_ID
||
!process.env.GOOGLE_CLIENT_SECRET
||
!process.env.GOOGLE_USER_URL
||
!process.env.GOOGLE_TOKEN_URL
||
!process.env.GOOGLE_REDIRECT_URI
){
throw new Error('INVALID ENV FILES')
}

const CLIENT_ID = process.env.GOOGLE_CLIENT_ID
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET
const USER_URL = process.env.GOOGLE_USER_URL
const TOKEN_URL = process.env.GOOGLE_TOKEN_URL
const REDIRECT_URI = process.env.GOOGLE_REDIRECT_URI

const googleTempToken = await OAuth.exchangeCodeForAccessToken(
context.request.payload.code,
CLIENT_ID,
CLIENT_SECRET,
TOKEN_URL,
REDIRECT_URI
) //swap code for access token

const googleTempUser = await OAuth.fetchUser(
googleTempToken.access_token ,
USER_URL,
CLIENT_ID,
'json'
) // get google user data

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

if(userError){
//Check what user error return
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: googleTempUser.name,
active: true,
google_id: googleTempUser.sub.toString(),
roles: ['root'],
email: `${googleTempUser.name}@user.template.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)
}
}
//if user already exists in database just authenticate and return result to web
return Result.result(await successfulAuthentication(user._id, context))
}
74 changes: 74 additions & 0 deletions api/src/routes/implementations/twitch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { ACError, type RouteContext, Result, successfulAuthentication } from 'aeria'
import {OAuth} from '../../oauth.js'


export const twitch = async(context:RouteContext)=>{
if(
!process.env.TWITCH_CLIENT_ID
||
!process.env.TWITCH_CLIENT_SECRET
||
!process.env.TWITCH_USER_URL
||
!process.env.TWITCH_TOKEN_URL
||
!process.env.TWITCH_REDIRECT_URI
){
throw new Error('INVALID ENV FILES')
}

const CLIENT_ID = process.env.TWITCH_CLIENT_ID
const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET
const USER_URL = process.env.TWITCH_USER_URL
const TOKEN_URL = process.env.TWITCH_TOKEN_URL
const REDIRECT_URI = process.env.TWITCH_REDIRECT_URI

const twitchTempToken = await OAuth.exchangeCodeForAccessToken(
context.request.payload.code,
CLIENT_ID,
CLIENT_SECRET,
TOKEN_URL,
REDIRECT_URI
) //swap code for access token

const twitchTempUser = await OAuth.fetchUser(
twitchTempToken.access_token ,
USER_URL,
CLIENT_ID,
'application/vnd.twitchtv.v5+json'
) // get twitch user data

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

if(userError){
//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: twitchTempUser.login,
active: true,
twitch_id: twitchTempUser.id.toString(),
roles: ['root'],
email: `${twitchTempUser.login}@user.template.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)
}
}
//if user already exists in database just authenticate and return result to web
return Result.result(await successfulAuthentication(user._id, context))
}
Loading

0 comments on commit a068768

Please sign in to comment.