Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

DEPRECATED - Phoenix Authentication library that wraps Guardian for extra functionality

License

NotificationsYou must be signed in to change notification settings

britton-jb/sentinel

Repository files navigation

Build Status

Note

Currently master (this readme) and the latest hex release have diverged dueto poor planning on my part while working on the next version ofSentinel. It also currently interacts poorly with the new directorystructure of Phoenix 1.3. I'm currently working on an update to remedythis, but cannot promise it will be released soon.

If you'd like to assist in developing the latest version of Sentinelplease reach out to me.

Things I wishGuardian includedout of the box, likeUeberauth integration, routing,invitation flow, confirmation emails, and, password reset emails.It's just a thin wrapper on Guardian but everybody shouldn't have to rollthis themselves when they build stuff.

I do my best to followsemantic versioning with thisrepo.

Suggestions? See theContributing/Want something new?section.

Want an example app? CheckoutSentinelExample.

Installation

Here's how to add it to your Phoenix project, and things you need tosetup:

# mix.exs# Requires Elixir ~> 1.3defpdepsdo# ...{:sentinel,"~> 2.0"},{:guardian_db,"~> 0.8.0"},# If you'd like to database back your tokens, and prevent replayability# ...end

Configure Guardian

Example config:

# config/config.exsconfig:guardian,Guardian,allowed_algos:["HS512"],# optionalverify_module:Guardian.JWT,# optionalissuer:"MyApp",ttl:{30,:days},verify_issuer:true,# optionalsecret_key:"guardian_sekret",serializer:Sentinel.GuardianSerializer,hooks:GuardianDb# optional if using guardiandb

More info

Optionally Configure GuardianDb

config:guardian_db,GuardianDb,repo:MyApp.Repo

The install task which ships with Sentinel, which you will run later inthis walkthrough, creates the migration for the GuardianDb tokens.

Configure Sentinel

# config/config.exsconfig:sentinel,app_name:"Test App",user_model:Sentinel.User,# should be your generated modelsend_address:"test@example.com",crypto_provider:Comeonin.Bcrypt,repo:Sentinel.TestRepo,ecto_repos:[Sentinel.TestRepo],auth_handler:Sentinel.AuthHandler,layout_view:MyApp.Layout,# your layoutlayout::app,views:%{email:Sentinel.EmailView,# your email view (optional)error:Sentinel.ErrorView,# your error view (optional)password:Sentinel.PasswordView,# your password view (optional)session:Sentinel.SessionView,# your session view (optional)shared:Sentinel.SharedView,# your shared view (optional)user:Sentinel.UserView# your user view (optional)},router:Sentinel.TestRouter,# your routerendpoint:Sentinel.Endpoint,# your endpointinvitable:true,invitation_registration_url:"http://localhost:4000",# for api usage onlyconfirmable::optional,confirmable_redirect_url:"http://localhost:4000",# for api usage onlypassword_reset_url:"http://localhost:4000",# for api usage onlysend_emails:true,user_model_validator:{MyApp.Accounts,:custom_changeset},# your custom validatorregistrator_callback:{MyApp.Accounts,:setup}# your callback function (optional)

Seeconfig/test.exs for an example of configuring Sentinel

invitation_registration_url,confirmable_redirect_url, andpassword_reset_url are three configuration settings that must be setif using the API routing in order to have some place to be directed toafter completing the relevant server action. In most cases I'danticipate this being a page of a SPA, Mobile App, or other clientinterface.

Configure Ueberauth

# config/config.exsconfig:ueberauth,Ueberauth,providers:[identity:{Ueberauth.Strategy.Identity,[param_nesting:"user",callback_methods:["POST"]]},]

Currently Sentinel is designed in such a way that the Identity Strategymust setparams_nesting as"user". This is something that I wouldlike to modify in future versions.

You'd also want to add other Ueberauth provider configurations at thispoint, as described in the respective provider documentation.

Configure Bamboo Mailer

# config/config.exsconfig:sentinel,Sentinel.Mailer,adapter:Bamboo.TestAdapter

More info

Run the install Mix task

Create the database using Ecto if it doesn't yet exist.

mixsentinel.install

This will create a user model if it doesn't already exist, add amigration for GuardianDb migration, and add a migration for Ueberauthprovider credentials.

You will want to delete the GuardianDb migration if you're choosing notto use it.

Currently the install task outputs the following warning:

warning: the :datetime type in migrations is deprecated, please use:utc_datetime or :naive_datetime instead

This is due to the fact that Phoenix's generators don't appear tosupportutc_datetime being passed in. Please modify the generatedmigration accordingly. Phoenix's generators also appear to not supportsettingnull: false with the migration generator, so you will wantto set that in the migration for the user email as well.

Mount the desired routes

defmoduleMyApp.RouterdouseMyApp.Web,:routerrequireSentinel# ...# ...scope"/"do# pipe_through, browser, api, or your own pipeline depending on your needs# pipe_through :browser# pipe_through :apiSentinel.mount_ueberauthendscope"/"dopipe_through:browserSentinel.mount_htmlendscope"/api",as::apidopipe_through:apiSentinel.mount_apiendend

Be aware that the routes mounted by the macroSentinel.mount_ueberauthmust be mounted on the root of your URL, due to the way Ueberauthmatches against routes.To illustrate, the route for requesting a given provider must beexample.com/auth/:provider. If it isexample.com/api/auth/:providerUeberauth will not properly register requests.

NOTE: You will run into an issue here if you set the scope toscope "/", MyApp.Router do.

The generated routes are shown in/lib/sentinel.ex:

Sentinel.mount_ueberauth

methodpathdescription
GET/loginLogin page
GET/logoutRequest logout
GET/auth/session/newLogin page
POST/auth/sessionRequest authentication
DELETE/auth/sessionRequest logout
GET/auth/:providerRequest specific Ueberauth provider login page
GET/auth/:provider/callbackCallback URL for Ueberauth provider
POST/auth/:provider/callbackCallback URL for Ueberauth provider

Sentinel.mount_html

methodpathdescription
GET/user/newNew user page
POST/userCreate new user
GET/user/:id/invitedInvited user registration form
PUT/user/:id/invitedComplete user invitation flow
GET/user/confirmation_instructionsRequest resending confirmation instructions page
POST/user/confirmation_instructionsRequest confirmation instructions email
GET/user/confirmationConfirm user email address from email
GET/password/newForgot password page
POST/password/newRequest password reset email
GET/password/editPassword reset page
PUT/passwordReset password
GET/accountBasic user edit page
PUT/accountUpdate user information

Sentinel.mount_api

methodpathdescription
GET/user/:id/invitedRedirect user from email link to invited user registration form
PUT/user/:id/invitedComplete user invitation flow
GET/user/confirmation_instructionsRequest resending confirmation instructions
GET/user/confirmationConfirm user email address from email
GET/password/newRequest password reset email
GET/password/editRequest password reset page from email
PUT/passwordReset password
GET/accountRequests user account
PUT/accountUpdate user information
PUT/account/passwordUpdate user password separately

Overriding the Defaults

Confirmable

By default users are not required to confirm their account to login. Ifyou'd like to require confirmation set theconfirmable configurationfield to:required. If you don't want confirmation emails sent, setthe field to:false. The default is:optional.

Invitable

By default, users are required to have a password upon creation. Ifyou'd like to enable users to create accounts on behalf of other userswithout a password you can set theinvitable configuration field totrue. This will result in the user being sent an email with a link toGET users/:id/invited, which you can complete by posting to the sameURL, with the following params:

{"confirmation_token":"confirmation_token_from_email_provided_as_url_param","password_reset_token":"password_reset_token_from_email_provided_as_url_param","password":"newly_defined_user_password"}

Custom Routes

If you want to customize the routes, or use your own controllerendpoints you can do that by overriding the individual routes listed.

Generate custom views

If you want to use custom views, you'll need copy over the views and templatesto your application. Sentinel provides a mix task make this a one-liner:

mix sentinel.gen.views

This mix task accepts a single argument of the specific context. This value canbe "email", "error", "password", "session", "shared", or "user". Once you copyover a context's view and templates, you must update the config to point toyour application's local files:

config :sentinel, views: %{user: MyApp.Web.UserView}

The keys for this views config map correspond with the list of contexts above.

Auth Error Handler

If you'd like to write your own custom authorization or authenticationhandler change theauth_handler Sentinel configuration optionto the module name of your handler.

It must define two functions,unauthorized/2, andunauthenticated/2,where the first parameter is the connection, and the second isinformation about the session.

Custom model validator

If you want to add custom changeset validations to the user model, you can dothat by specifying a user model validator:

config:sentinel,user_model_validator:{MyApp.Accounts,:custom_changeset}

This function must accept 2 arguments consisting of a changeset and a map ofparams andmust return a changeset. The params in the second argument will bethe raw params from the original request (not the ueberauth callback params).

defcustom_changeset(changeset,attrs\\%{})dochangeset|>cast(attrs,[:my_attr])|>validate_required([:my_attr])|>validate_inclusion(:my_attr,["foo","bar"])end

Contributing/Want something new?

Create an issue. Preferably with a PR. If you're super awesomeinclude tests.

As you recall from the license, this is provided as is. I don't make anymoney on this, so I do support when I feel like it. That said, I want todo my best to contribute to the Elixir/Phoenix community, so I'll dowhat I can.

Having said that if you bother to put up a PR I'll take a look, andeither merge it, or let you know what needs to change before I do.Having experienced sending in PRs and never hearing anything aboutthem, I know it sucks.

About

DEPRECATED - Phoenix Authentication library that wraps Guardian for extra functionality

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors7


[8]ページ先頭

©2009-2026 Movatter.jp