Git Product home page Git Product logo

adonis-api-app's People

Contributors

abijeet avatar alanaasmaa avatar ammezie avatar c5n8 avatar chrisbbreuer avatar dattn avatar enzyofficial avatar firsyura avatar ibuffering avatar kevmt avatar mzanggl avatar romainlanz avatar thetutlage avatar vincevannoort avatar willvincent avatar xstoudi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adonis-api-app's Issues

JWT token based auth not working

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']);

Response
jwt

I passed header also.check this any issues.

JWT login error

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"
	}
]

Register Message
register

Login Message
login

Shouldn't adonis-api-app template disabled by default csrf protection

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.

Error responses in JSON

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?

EADDRINUSE when adonis is automatically reloaded.

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.

See the print bellow:
screen shot 2018-02-05 at 10 25 04

Can you help me to solve this issue?

Supports typescript

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

Action required: Greenkeeper could not be activated 🚨

🚨 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.

User token relationship .onDelete('CASCADE') to blueprint

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? 🤔

Updating user password issue

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.

Convert password hashing into a smarter trait

Related to adonisjs/lucid#198

This one kind of bit me, I was doing a big data import and didn't realize it was bcrypting 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.)

Scheme type api is not working, it showing error "Missing or Invalid Token"

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.

Missing Env reference in hash configuration file

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.