-
In the code below i have an This is my hack to solve this problem. I need a better solution. How to do the import { AuthenticationException } from '@adonisjs/auth/build/standalone'
import { GuardsList } from '@ioc:Adonis/Addons/Auth'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Env from '@ioc:Adonis/Core/Env'
import LDAP from 'ldap-authentication'
import { base64 } from '@ioc:Adonis/Core/Helpers'
/**
* Auth middleware is meant to restrict un-authenticated access to a given route
* or a group of routes.
*
* You must register this middleware inside `start/kernel.ts` file under the list
* of named middleware.
*/
export default class AuthMiddleware {
public async ldapAuth(guard: string, credentials?: string) {
if (!credentials)
throw new AuthenticationException(
'Necessária autenticação no sistema',
'E_UNAUTHORIZED_ACCESS',
guard
)
const [username, password] = base64.decode(credentials.split(' ')[1]).split(':')
try {
await LDAP.authenticate({
ldapOpts: {
url: Env.get('LDAP_HOST'),
},
adminDn: Env.get('LDAP_ADMIN_DN'),
adminPassword: Env.get('LDAP_ADMIN_PASSWORD'),
userSearchBase: Env.get('LDAP_USER_SEARCH_BASE'),
usernameAttribute: Env.get('LDAP_USER_ATTRIBUTE'),
username: username,
userPassword: password,
})
} catch (error) {
const jsonError = JSON.stringify(error, null, 2)
throw new AuthenticationException(
`Erro ao tentar autenticar no LDAP com usuário ${username} -> ${jsonError}`,
'E_UNAUTHORIZED_ACCESS',
guard
)
}
}
/**
* Authenticates the current HTTP request against a custom set of defined
* guards.
*
* The authentication loop stops as soon as the user is authenticated using any
* of the mentioned guards and that guard will be used by the rest of the code
* during the current request.
*/
protected async authenticate(
auth: HttpContextContract['auth'],
guards: (keyof GuardsList)[],
credentials?: string
) {
/**
* Hold reference to the guard last attempted within the for loop. We pass
* the reference of the guard to the "AuthenticationException", so that
* it can decide the correct response behavior based upon the guard
* driver
*/
let guardLastAttempted: string | undefined
for (let guard of guards) {
guardLastAttempted = guard
await this.ldapAuth(guard, credentials)
if (await auth.use(guard).check()) {
/**
* Instruct auth to use the given guard as the default guard for
* the rest of the request, since the user authenticated
* succeeded here
*/
auth.defaultGuard = guard
return true
}
}
/**
* Unable to authenticate using any guard
*/
throw new AuthenticationException(
'Unauthorized access',
'E_UNAUTHORIZED_ACCESS',
guardLastAttempted
)
}
/**
* Handle request
*/
public async handle(
{ auth, request }: HttpContextContract,
next: () => Promise<void>,
customGuards: (keyof GuardsList)[]
) {
/**
* Uses the user defined guards or the default guard mentioned in
* the config file
*/
const guards = customGuards.length ? customGuards : [auth.name]
await this.authenticate(auth, guards, request.header('Authorization'))
await next()
}
}
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
My first attempt to create a LdapProvider is to create this class inside This is the correct way to extend the auth(inside AppProviders)? public async register() {
const LdapProvider = await import('./LdapProvider')
const auth = this.app.container.use('Adonis/Addons/Auth')
auth.extend('provider', 'ldap', (auth, mapping, config) => {
console.log("hey",auth, mapping, config )
return new LdapProvider();
})
} export default class LdapProvider<User> implements UserProviderContract<User> {
async getUserFor(user: User): Promise<ProviderUserContract<User>> {
throw new Error('getUserFor')
}
/**
* Find a user using the primary key value
*/
async findById(id: string | number): Promise<ProviderUserContract<User>> {
throw new Error('findbyid')
}
/**
* Find a user by searching for their uids
*/
async findByUid(uid: string): Promise<ProviderUserContract<User>> {
throw new Error('findByUid')
}
/**
* Find a user using the remember me token
*/
async findByRememberMeToken(
userId: string | number,
token: string
): Promise<ProviderUserContract<User>> {
throw new Error('findByRememberMeToken')
}
/**
* Update remember token
*/
async updateRememberMeToken(authenticatable: ProviderUserContract<User>): Promise<void> {
throw new Error('updateRememberMeToken')
}
} |
Beta Was this translation helpful? Give feedback.
My first attempt to create a LdapProvider is to create this class inside
providers
folder. I'm trying to do a a simple test but i have so many questions.How can i define the typings of my LdapProvider?
Where should i define a custom User interface for my LdapProvider?
This is the correct way to extend the auth(inside AppProviders)?