Skip to content

Commit

Permalink
use authSch 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Tschonti committed Aug 14, 2024
1 parent d613dcf commit 154e16a
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 63 deletions.
89 changes: 45 additions & 44 deletions src/components/users/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,60 +4,61 @@ import { RoleType, User } from './user'
import { asyncWrapper } from '../../util/asyncWrapper'

interface OAuthUser {
displayName: string
internal_id: string
mail?: string
name: string
sub: string
email?: string
}

export const getUser = asyncWrapper(async (req: Request, res: Response, next: NextFunction) => {
const user = await User.query()
.findOne({ id: parseInt(req.params.id) })
.withGraphFetched('groups(orderByEndDate)')
.modifiers({
orderByEndDate(builder) {
builder.orderBy('endDate', 'DESC')
}
})
export const getUser = asyncWrapper(
async (req: Request, res: Response, next: NextFunction) => {
const user = await User.query()
.findOne({ id: parseInt(req.params.id) })
.withGraphFetched('groups(orderByEndDate)')
.modifiers({
orderByEndDate(builder) {
builder.orderBy('endDate', 'DESC')
},
})

if (!user) {
res.render('error/not-found')
} else {
req.userToShow = user
next()
if (!user) {
res.render('error/not-found')
} else {
req.userToShow = user
next()
}
}
})
)

export const updateRole = asyncWrapper(async (req: Request, res: Response, next: NextFunction) => {
const user = await User.query().findOne({ id: parseInt(req.params.id) })
export const updateRole = asyncWrapper(
async (req: Request, res: Response, next: NextFunction) => {
const user = await User.query().findOne({ id: parseInt(req.params.id) })

if (!user) {
res.redirect('/not-found')
} else {
await User.query()
.patch({ role: req.body.role })
.where({ id: user.id })
next()
if (!user) {
res.redirect('/not-found')
} else {
await User.query().patch({ role: req.body.role }).where({ id: user.id })
next()
}
}
})
)

export const updateUser = asyncWrapper(async (req: Request, res: Response, next: NextFunction) => {
const id = req.user.id
const { floor, wantEmail } = req.body
req.user = await User.query().patchAndFetchById(id, { floor, wantEmail })
export const updateUser = asyncWrapper(
async (req: Request, res: Response, next: NextFunction) => {
const id = req.user.id
const { floor, wantEmail } = req.body
req.user = await User.query().patchAndFetchById(id, { floor, wantEmail })

next()
})
next()
}
)

export const createUser = async (user: OAuthUser): Promise<User> => {
return await User.transaction(async trx => {
return await User.query(trx)
.insert(
{
name: user.displayName,
email: user.mail,
authSchId: user.internal_id,
role: RoleType.USER
}
)
return await User.transaction(async (trx) => {
return await User.query(trx).insert({
name: user.name,
email: user.email,
authSchId: user.sub,
role: RoleType.USER,
})
})
}
50 changes: 31 additions & 19 deletions src/config/passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,21 @@ passport.use(
tokenURL: `${AUTH_SCH_URL}/oauth2/token`,
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
scope: ['basic', 'displayName', 'mail']
scope: ['openid', 'profile', 'email'],
},
async (
accessToken: string,
_refreshToken: string,
_profile: unknown,
done: (err: Error, user: User) => void
) => {
const responseUser = await fetch(
`${AUTH_SCH_URL}/api/profile?access_token=${accessToken}`
).then(res => res.json())
const responseUser = await fetch(`${AUTH_SCH_URL}/oidc/userinfo`, {
headers: { Authorization: `Bearer ${accessToken}` },
}).then((res) => res.json())

const user = await User.query().findOne({ authSchId: responseUser.internal_id })
const user = await User.query().findOne({
authSchId: responseUser.sub,
})

if (user) {
done(null, user)
Expand All @@ -55,29 +57,39 @@ passport.deserializeUser(async (id: number, done) => {
* Login Required middleware.
*/
export const isAuthenticated =
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
(req: Request, res: Response, next: NextFunction): Response<any, Record<string, any>> => {
const contentType = req.headers['content-type']
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
(
req: Request,
res: Response,
next: NextFunction
): Response<any, Record<string, any>> => {

Check warning on line 65 in src/config/passport.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

Check warning on line 65 in src/config/passport.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const contentType = req.headers['content-type']

if (req.isAuthenticated()) {
next()
} else {
if ((contentType &&
(contentType.indexOf('application/json') !== 0 ||
contentType.indexOf('multipart/form-data') !== 0)) ||
req.method !== 'GET') {
return res.sendStatus(401)
if (req.isAuthenticated()) {
next()
} else {
if (
(contentType &&
(contentType.indexOf('application/json') !== 0 ||
contentType.indexOf('multipart/form-data') !== 0)) ||
req.method !== 'GET'
) {
return res.sendStatus(401)
}
res.render('error/not-authenticated')
}
res.render('error/not-authenticated')
}
}

/**
* Authorization Required middleware.
*/
export const requireRoles = (...roles: RoleType[]) => {
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
return (req: Request, res: Response, next: NextFunction): Response<any, Record<string, any>> => {
return (
req: Request,
res: Response,
next: NextFunction
): Response<any, Record<string, any>> => {

Check warning on line 92 in src/config/passport.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

Check warning on line 92 in src/config/passport.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const role = req.user?.role
if (roles.some((element) => role == element)) {
next()
Expand Down

0 comments on commit 154e16a

Please sign in to comment.