더북(TheBook)

10.7.2 로그인 기능 구현

 

로그인/로그아웃 액션

Go에는 다양한 인증 패키지가 있지만 여기서는 세션에 저장된 사용자 정보를 확인하는 방식으로 인증을 처리한다. 로그인할 때 아이디와 패스워드를 비교하여 일치하면 현재 접속한 사용자 정보를 세션에 저장하고, 모든 요청을 처리할 때 세션에 저장된 사용자 정보를 확인하여 접근이 허용됐을 때만 이후 로직을 처리하게 해보자.

로그인/로그아웃을 구현하려면 Login 메서드, CreateSession 메서드, DestroySession 메서드가 필요하다. Login 메서드는 로그인 페이지로 렌더링하고, CreateSession 메서드는 usernamepassword로 인증을 확인한 후 세션 정보를 생성하며, DestroySession 메서드는 로그아웃을 처리한다.

revel new goblog 명령으로 Revel 웹 애플리케이션을 생성할 때 자동으로 생성된 app/controllers/app.go 파일을 다음과 같이 재작성한다.

▼ app/controllers/app.go

package controllers
 
import (
    “goblog/app/models”
 
“golang.org/x/crypto/bcrypt” “github.com/revel/revel” ) type App struct { GormController } func (c App) Login() revel.Result { return c.Render() } func (c App) CreateSession(username, password string) revel.Result { var user models.User
// ➊ username으로 사용자 조회 c.Txn.Where(&models.User{Username: username}).First(&user)
// ➋ bcrypt 패키지의 CompareHashAndPassword 함수로 패스워드 비교 err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
// ➌ 패스워드가 일치하면 세션 생성후 포스트 목록 화면으로 이동 if err == nil { authKey := revel.Sign(user.Username) c.Session[“authKey”] = authKey c.Session[“username”] = user.Username c.Flash.Success(“Welcome, “ + user.Name) return c.Redirect(Post.Index) }
// ➍ 세션 정보를 모두 제거하고 홈으로 이동 for k := range c.Session { delete(c.Session, k) } c.Flash.Out[“username”] = username c.Flash.Error(“Login failed”) return c.Redirect(Home.Index) } func (c App) DestroySession() revel.Result { // clear session for k := range c.Session { delete(c.Session, k) } return c.Redirect(Home.Index) }

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.