开发者

How do I implement basic authentication with sessions in Rails?

开发者 https://www.devze.com 2023-01-21 08:51 出处:网络
Just learning Rails via 开发者_开发问答Michael Hartl\'s tutorial and one of the things we have to do is implement basic authentication with sessions instead of cookies.

Just learning Rails via 开发者_开发问答Michael Hartl's tutorial and one of the things we have to do is implement basic authentication with sessions instead of cookies.

I am trying to find any literature online that discusses it, but can't find anything.

The Rails Guides talk about sessions from a security point of view, so they assume you have your authentication working and everything - and are just interested in securing it.

But I would like to roll my own from scratch - a very simple version, nothing fancy at all.

Can someone explain to me, how a basic authentication system would work/look like in Rails 3 or show me some articles and stuff that explain how to roll my own.

Again, doesn't have to be fancy, I just want to understand how they work.

Also, assume that a User model has been created, and user data is stored in a db. So it's just a matter of confirming that there was a successful sign in, and showing them different content.

Thanks.


I figured it out, basically in my sessions controller I did this:

class SessionsController < ApplicationController

    def create
        user = User.authenticate(params[:session][:email], params[:session][:password])

        if user.nil?
            flash.now[:error] = "Invalid email/password combination."
            render 'new'
        else
            session[:user_id] = user.id
            redirect_to user
        end
    end

    def destroy
        session[:user_id] = nil
        redirect_to root_path
    end 
end
0

精彩评论

暂无评论...
验证码 换一张
取 消