adonisjs / adonis-api-app Goto Github PK
View Code? Open in Web Editor NEWAdonisJS 4 - Boilerplate for API server with pre-configured JWT
AdonisJS 4 - Boilerplate for API server with pre-configured JWT
I am using JWT token based auth in Adonis API. Login API working fine. I cant use the jwt auth check for other routes.
for example, Admin login success full, but that same admin auth check not working other activities.
My Routes:
Route.group(() => {
Route.get('user', 'UserController.index');
Route.post('addUser', 'UserController.store');
Route.get('getUser/:id', 'UserController.showId').middleware(['auth:jwt']);
Route.put('updateUser/:id', 'UserController.userUpdate');
Route.delete('deleteUser/:id', 'UserController.remove');
Route.post('login', 'UserController.login');
Route.get('check', 'UserController.check').middleware(['auth:jwt']);
}).prefix('api/v2');
My auth.js
jwt: {
serializer: 'lucid',
model: 'App/Models/User',
scheme: 'jwt',
uid: 'email',
password: 'password',
options: {
secret: 'self::app.appKey'
}
}
}
User controller:
async login({request, auth, response}) {
const {email, password} = request.all();
let token = await auth.attempt(email, password);
return response.status(200).json({data: token, message: 'Login successfull', status: true});
}
Its working fine.
But i want to check get users from DB using id passing in url with auth check it's not working.
//get by id
async showId({params, response, auth}) {
try {
let play = await auth.generate(user);
console.log(play);
let userInfo = await User.find(params.id)
if (userInfo != null) {
return response.json({data: userInfo, auth: auth, message: 'get the record', status: true})
}
return response.status(404).json(notFound)
} catch (error) {
response.send('Missing or invalid jwt token')
}
}
URL : oute.get('getUser/:id', 'UserController.showId').middleware(['auth:jwt']);
I passed header also.check this any issues.
There is any reason to not define 'Adonis/Middleware/AuthInit' in global middleware as is indicated in instructions?
adonis-api-app/start/kernel.js
Line 15 in df3b661
https://github.com/adonisjs/adonis-auth/blob/develop/instructions.md#register-global-middleware
https://adonisjs.com/docs/4.1/authentication#_registering_middleware
I am new to Adonis.
I am having a problem logging.
config/auth.js
{
authenticator: 'jwt',
jwt: {
serializer: 'lucid',
model: 'App/Models/User',
scheme: 'jwt',
uid: 'username',
password: 'password',
options: {
secret: Env.get('APP_KEY')
}
}
}
start/routes.js
const Route = use('Route')
Route.group(() => {
Route.post('/login', 'AuthController.login')
Route.post('/register', 'AuthController.register')
}).prefix('api/v1')
app/Controllers/Http/AuthController
async login ({ request, response, auth }) {
const { username, password } = request.all()
let token = await auth.attempt(username, password);
return response.status(200)
.json({
data: token,
message: 'Login successfull',
status: true
});
}
// Dont worry, this is just for testing purposes
async register ({ request, response, auth }) {
const { username, password, email } = request.all()
const hashedPass = await Hash.make(password)
const user = await User.create({
username: username,
password: hashedPass,
email: email,
})
return response.status(200)
.json({
message: 'registered successfull',
status: true
});
}
I can successfully register users, but when I try login, I get this error
[
{
"field": "password",
"message": "Invalid user password"
}
]
Any reason why package-lock.json
is in the .gitignore
by default?
Line 11 in de45760
package-lock.json
in .gitignore again
3 outdated packages with high risk persist at the moment
Hi,
I think its far the most question asked on adonisjs gitter. A lot of people are confused with csrf and api-only app. Shouldn't csrf protection be disabled in this template? I'd be happy to fix it if its the proper behavior though I can't find any shield.js file in this template.
I just noticed that if i create a new Controller using
adonis make:controller <name> --resource
it will create a new file with all route resources but the last one is called delete, and looking into the docs it should be destroy.
Some error responses such as 404
are returning HTML. Is there a setting to respond with JSON since this app is intended to be just an API?
Hi,
I'm using:
MacOS 10.12.6
NodeJS 8.9.0
Adonis 4.0 API Only blueprint
The problem is:
When i start the adonis using command "adonis serve --dev", adonis is started successfully, but when i make some code changes and adonis automatically reloads, the adonis crash and show me the error EADDRINUSE. It is like adonis try to reload but do not stop the instance correctly, so they try to restart without kill the process, and it causes an issue with port in use.
Can you help me to solve this issue?
Is there any example, or implementation to use typescript with this structure? And cli would be nice if this option is available adonis new yardstick --api-only --ts
🚨 You need to enable Continuous Integration on all branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.
Since we did not receive a CI status on the greenkeeper/initial
branch, we assume that you still need to configure it.
If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/
.
We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial
branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.
Currently when I try to delete user I get error:
ERROR: update or delete on table "users" violates foreign key constraint "tokens_user_id_foreign" on table "tokens"
I usually modify token migration to include .onDelete('CASCADE') to user and token relation in https://github.com/adonisjs/adonis-api-app/blob/master/database/migrations/1503250034280_token.js#L10
Then I don't have to worry about clearing user tokens before I delete user itself.
Perhaps it can added into blueprint(s) by default?
Or will it cause problems with some databases? 🤔
Hi.
I am facing an issue when the user forgots/wants to change his/her password.
My backend (AdonisJS API-only) config:
DATABASE = mariadb
AUTH = JWT (tokens are configured to expire within 5 minutes)
My User model only has the fields:
Id, email, password, timestamps.
Snippet of my update method.
const User = use('App/Models/User')
const Env = use('Env')
async update ({ request, response }) {
const {password} = await request.only(['password'])
let user = await User.findBy('email', Env.get('CORREO_EMPRESA'))
if (!user) {
return response.status(400).send(false)
}
user.password = password
if (!await user.save()) {
return response.status(500).send(false)
}
return response.status(200).send(true)
}
This method has the auth middleware, which the user generates a JWT Token when clicking the Reset password button at the front end (Angular) and is sent to the user email.
Snippet of my temporary jwt token request method
Route.get('password-token', async ({response, auth}) => {
const token = await auth.generate(await User.findBy('email', Env.getOrFail('CORREO_EMPRESA')))
//return token.token
const message = `${token.token} <p><strong>Este token es válido solo por 5 minutos.</strong></p>`
const reply = await sendMail.sendMail({
emailConfig: emailSenderConfig,
to: Env.getOrFail('CORREO_EMPRESA'),
subject: 'Cambio de contraseña para cuenta de CFDI GEN.',
content: message,
})
console.log(reply)
return response.status(200).send(true);
})
Everything seems to work just fine when updating the model (password), i confirm the password field modification using the mariadb cli-client
But when i try to log in once the password has been updated, i get this exception:
[
{
"field": "password",
"message": "Invalid user password"
}
]
Snippet of my log in method
async login ({ request, response, auth }) {
const { email, password } = await request.only(['email','password'])
return response.status(200).json(await auth.withRefreshToken().attempt(email, password))
}
Before updating the user password, the log attempt method executes correctly and returns the auth object with the token and refresh token properties but when the user password is updated, it does not.
I've tried to execute the toString() method in the password when updating the user password but does not work.
My User model snippet
class User extends Model {
static boot () {
super.boot()
/**
* A hook to hash the user password before saving
* it to the database.
*/
this.addHook('beforeSave', async (userInstance) => {
if (userInstance.dirty.password) {
userInstance.password = await Hash.make(userInstance.password)
}
})
this.addHook('beforeUpdate', async (userInstance) => {
if (userInstance.dirty.password) {
userInstance.password = await Hash.make(userInstance.password)
}
})
}
/**
* A relationship on tokens is required for auth to
* work. Since features like `refreshTokens` or
* `rememberToken` will be saved inside the
* tokens table.
*
* @method tokens
*
* @return {Object}
*/
tokens () {
return this.hasMany('App/Models/Token')
}
static get hidden() {
return ['password']
}
}
And no, i am not hashing the password when submitting the patch http request body to update the user password, only the user hooks are hashing it.
For "time saving", i am using/testing my adonisjs api with insomnia instead of angular.
What could be the problem(s) ? Do i have to remove one of the hooks ?
Any help/advice/fix is very appreciated
Thanks in advance.
Related to adonisjs/lucid#198
This one kind of bit me, I was doing a big data import and didn't realize it was bcrypt
ing every model instance.
I'd like to do something like this:
User.unguardPasswords()
...bulk import...
User.guardPasswords()
(In order to do this, Lucid needs a good way of allowing traits to add properties to the __setters__
array.)
If we check the constructor there is an API type for auth, and its missing when we start a new project.
My auth.js looks like
'use strict'
/** @type {import('@adonisjs/framework/src/Env')} */
const Env = use('Env')
module.exports = {
/*
|--------------------------------------------------------------------------
| Authenticator
|--------------------------------------------------------------------------
|
| Authentication is a combination of serializer and scheme with extra
| config to define on how to authenticate a user.
|
| Available Schemes - basic, session, jwt, api
| Available Serializers - lucid, database
|
*/
authenticator: 'api',
/*
|--------------------------------------------------------------------------
| Session
|--------------------------------------------------------------------------
|
| Session authenticator makes use of sessions to authenticate a user.
| Session authentication is always persistent.
|
*/
session: {
serializer: 'LucidMongo',
model: 'App/Models/User',
scheme: 'session',
uid: 'email',
password: 'password'
},
/*
|--------------------------------------------------------------------------
| Basic Auth
|--------------------------------------------------------------------------
|
| The basic auth authenticator uses basic auth header to authenticate a
| user.
|
| NOTE:
| This scheme is not persistent and users are supposed to pass
| login credentials on each request.
|
*/
basic: {
serializer: 'LucidMongo',
model: 'App/Models/User',
scheme: 'basic',
uid: 'email',
password: 'password'
},
/*
|--------------------------------------------------------------------------
| Jwt
|--------------------------------------------------------------------------
|
| The jwt authenticator works by passing a jwt token on each HTTP request
| via HTTP `Authorization` header.
|
*/
jwt: {
serializer: 'LucidMongo',
model: 'App/Models/User',
scheme: 'jwt',
uid: 'email',
password: 'password',
expiry: '1m',
options: {
secret: Env.get('APP_KEY')
}
},
/*
|--------------------------------------------------------------------------
| Api
|--------------------------------------------------------------------------
|
| The Api scheme makes use of API personal tokens to authenticate a user.
|
*/
api: {
serializer: 'LucidMongo',
scheme: 'api',
model: 'App/Models/User',
uid: 'email',
password: 'password',
expiry: '30d',
},
}
My logout function uses auth middleware.
Route.post('/api/v1/logout', 'AuthController.logout').as('logout').middleware('auth')
Now when i request this from Postman tool am getting error as "E_INVALID_API_TOKEN: The api token is missing or invalid"
Am using Mongo db, and i have generated token using attempt method while login
await auth.attempt(uid, password)
Am also passing bearer token in postman which i got from attempt method.
"token": {
"type": "bearer",
"token": "0a957d5a02a62954b38e8b1e848462d2M2BDMqc72R0z3oRsUCkqyoUTknz7V/Q7AJ6OOVcU1crgOAz8uvQNgUUAzaIadSNH"
}
Still am getting same error that token is missing...please help me understand what is wrong here. Thanks.
I created an api-only project and when I tried to run it, Adonis raised ReferenceError: Env is not defined
at line 13. I looked it up and confirmed that there is in fact no reference to the Env module.
I looked into the other config files that used Env and I found out that there was missing line const Env = use('Env')
in the hash config file.
Hope this helps.
Steps to reproduce:
adonis new project --api-only
adonis serve --dev
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.