- Notifications
You must be signed in to change notification settings - Fork18
DEPRECATED - Phoenix Authentication library that wraps Guardian for extra functionality
License
britton-jb/sentinel
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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.
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
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
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.
# 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.
# 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.
# config/config.exsconfig:sentinel,Sentinel.Mailer,adapter:Bamboo.TestAdapter
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 insteadThis 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.
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:
| method | path | description |
|---|---|---|
| GET | /login | Login page |
| GET | /logout | Request logout |
| GET | /auth/session/new | Login page |
| POST | /auth/session | Request authentication |
| DELETE | /auth/session | Request logout |
| GET | /auth/:provider | Request specific Ueberauth provider login page |
| GET | /auth/:provider/callback | Callback URL for Ueberauth provider |
| POST | /auth/:provider/callback | Callback URL for Ueberauth provider |
| method | path | description |
|---|---|---|
| GET | /user/new | New user page |
| POST | /user | Create new user |
| GET | /user/:id/invited | Invited user registration form |
| PUT | /user/:id/invited | Complete user invitation flow |
| GET | /user/confirmation_instructions | Request resending confirmation instructions page |
| POST | /user/confirmation_instructions | Request confirmation instructions email |
| GET | /user/confirmation | Confirm user email address from email |
| GET | /password/new | Forgot password page |
| POST | /password/new | Request password reset email |
| GET | /password/edit | Password reset page |
| PUT | /password | Reset password |
| GET | /account | Basic user edit page |
| PUT | /account | Update user information |
| method | path | description |
|---|---|---|
| GET | /user/:id/invited | Redirect user from email link to invited user registration form |
| PUT | /user/:id/invited | Complete user invitation flow |
| GET | /user/confirmation_instructions | Request resending confirmation instructions |
| GET | /user/confirmation | Confirm user email address from email |
| GET | /password/new | Request password reset email |
| GET | /password/edit | Request password reset page from email |
| PUT | /password | Reset password |
| GET | /account | Requests user account |
| PUT | /account | Update user information |
| PUT | /account/password | Update user password separately |
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.
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"}If you want to customize the routes, or use your own controllerendpoints you can do that by overriding the individual routes listed.
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.
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.
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
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors7
Uh oh!
There was an error while loading.Please reload this page.