2015-10-22

beego Tutorial 11 : 로그인/로그아웃 처리하기


  • 명색이 관리자 화면인데, 아무나 들어와서 조작하면 안되겠지요? 이제는 마지막으로 로그인/로그아웃 처리를 해보겠습니다. 로그인/로그아웃은 세션을 이용해서 구현합니다.
  • 로그인 화면을 구성합니다. xyz/views/index.html 을 작성합니다.
    <!DOCTYPE html>
    <html lang="ko">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_xsrf" content="{{.xsrf_token}}" />
    <title>Login</title>
    <link rel="stylesheet" href="/static/b/css/bootstrap.min.css">
    </head>
    <body>
     
    <div class="container" style="margin-top: 20px">
      <form action="/login" method="post" class="form-horizontal" style="margin: 0 auto; max-width: 360px;">
        {{ .xsrfdata }}
        <div class="form-group">
          <label for="userid" class="col-sm-3 control-label">아이디</label>
          <div class="col-sm-9">
            <input type="text" id="userid" name="userid" class="form-control" placeholder="당신의 ID를 입력하세요..." required autofocus>
          </div>
        </div>
        <div class="form-group">
          <label for="passwd" class="col-sm-3 control-label">비밀번호</label>
          <div class="col-sm-9">
            <input type="password" id="passwd" name="passwd" class="form-control" placeholder="비밀번호를 입력하세요..." required>
          </div>
        </div>
        <input type="submit" class="btn btn-primary btn-block" value="로그인" />
      </form>
    </div>
     
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="/static/b/js/bootstrap.min.js"></script>
    </body>
    </html>
  • xyz/controllers/main.go 를 다음처럼 수정합니다.
    package controllers
     
    import (
        "github.com/astaxie/beego"
        "html/template"
    )
     
    type MainController struct {
        beego.Controller
    }
     
    // 메인 로그인 화면
    func (c *MainController) Index() {
        c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())
        c.TplNames = "index.html"
    }
  • xyz/conf/app.conf 에 다음을 추가합니다.
    ...
    
    sessionon = true
    
    ...
  • xyz/models/admin.go 에 다음을 추가합니다.
    ...
     
    func (this *Admin) IsMember(userid string, passwd string) bool {
        sha := sha512.New()
        sha.Write([]byte(passwd))
        hashed_passwd := hex.EncodeToString(sha.Sum(nil))
     
        o := orm.NewOrm()
        o.Using("default")
        cnt, _ := o.QueryTable(this).Filter("userid", userid).Filter("password", hashed_passwd).Count()
     
        if cnt == 0 {
            return false
        }
     
        return true
    }
     
    ...
  • xyz/controllers/main.go 에 xyz/models 를 import 하고, 다음을 추가한다.
    ...
     
    // 로그인
    func (c *MainController) Login() {
        userid := c.GetString("userid")
        passwd := c.GetString("passwd")
     
        admin := new(models.Admin)
        if is_member := admin.IsMember(userid, passwd); is_member == true {
            c.SetSession("login", true) // 로그인세션 등록
            c.Redirect(c.UrlFor("AdminController.Index"), 302)
            return
        }
     
        c.Redirect(c.UrlFor(".Index"), 302)
    }
     
    ...
  • xyz/routers/router.go 에 다음을 추가한다.
    ...
     
    beego.Router("/login", &c.MainController{}, "post:Login")
     
    ...
  • xyz/main.go 에 github.com/astaxie/beego/context 를 import 하고 다음을 Init() 안의 마지막에 추가한다.
    ...
     
        // Authetication
        var FilterUser = func(ctx *context.Context) {
            _, login := ctx.Input.Session("login").(bool)
            if login != true {
                ctx.Redirect(302, "/")
            }
        }
        beego.InsertFilter("/admin", beego.BeforeRouter, FilterUser)
        beego.InsertFilter("/admin/*", beego.BeforeRouter, FilterUser)
     
    ...
    여기까지 작성하면, 로그인해야만 http://localhost:8080/admin 을 접근할 수 있게 된다.
  • xyz/views/admin/index.html 에 다음을 적당한 곳에 추가한다.
    ...
     
    <a href="/logout">[로그아웃]</a>
     
    ...
  • xyz/controllers/main.go 에 다음을 추가한다.
    ...
     
    // 로그아웃
    func (c *MainController) Logout() {
        c.DestroySession()
        c.Redirect(c.UrlFor(".Index"), 302)
    }
     
    ...
  • xyz/routers/router.go 에 다음을 추가한다.
    ...
     
    beego.Router("/logout", &c.MainController{}, "get:Logout")
     
    ...
    이제, 로그인도 해보고, 로그아웃도 해보세요. ^^


댓글 1개:

  1. Beego에서 로그아웃시 이전페이지로 리다이렉트 하는 방법에 대하여 혹시 아시나요?

    답글삭제