Elixir, Phoenix에서 Login 페이지 만들기

10312 단어 ElixirPhoenixlogin
하고 싶은 것은 로그인 페이지에서 emailpassword 를 입력해, 로그인하면 유저 일람 페이지로 천이합니다.






먼저 사용자 목록 페이지를 준비하기 위해 Phoenix Ecto 관련 문서을 읽는 것이 좋습니다.

로그인 페이지는 그물에서 찾은 것를 사용하고 있습니다. 그 안에 Bootstrap3이 포함되어 있기 때문에 Bootstrap3도 사용하고 싶습니다. 자신의 이전 게시물를 참조하면 됩니다.
  • 프로젝트를 만듭니다. --no-brunch 에 대한 설명은 여기 에 있습니다.
  • 13:29:11 [N1210A001 => ~/Playground/elixir]
    $ mix phoenix.new hello_phoenix --no-brunch
    
  • 사용자 목록 페이지를 준비합니다. 아래 명령을 실행하면 hello_phoenix/priv/repo/migrations/ 디렉토리 아래에 migration 파일이 생성되어 나중에 사용하는 $ mix ecto.migrate 명령을 위해서입니다.
  • 13:34:30 [N1210A001 => ~/Playground/elixir/hello_phoenix]
    $ mix phoenix.gen.html User users name:string email:string password:string
    
  • resources "/users", UserControllerhello_phoenix/web/router.ex 에 추가합니다.
  • hello_phoenix_dev 데이터베이스를 만듭니다. hello_phoenix_dev를 만드는 이유는 hello_phoenix/config/dev.exs 파일에 정의되어 있습니다.
  • postgres 의 role가 없는 등의 에러 나오고 있는 경우는 이 페이지 그리고 대답은 찾을 수 있습니다.
    13:37:18 [N1210A001 => ~/Playground/elixir/hello_phoenix]
    $ mix ecto.create
    
  • 작성된 데이터베이스에 테이블을 작성하십시오.
  • 13:47:53 [N1210A001 => ~/Playground/elixir/hello_phoenix]
    $ mix ecto.migrate
    
  • 이제 앱을 시작해 보겠습니다. 아래 그림과 같아야 합니다.
  • 13:48:01 [N1210A001 => ~/Playground/elixir/hello_phoenix]
    $ mix phoenix.server
    



    * 화면에서 사용자를 여러 개 작성합니다.


  • Bootstrap3을 사용할 수 있도록 합니다. .
  • http://localhost:4000/ 에 액세스할 때 로그인 화면으로 합니다.

  • 1) hello_phoenix/web/templates/layout/application.html.eex 를 아래와 같이 수정합니다.
     <!DOCTYPE html>
     <html lang="en">
       <head>
         <meta charset="utf-8">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <meta name="description" content="">
         <meta name="author" content="">
    
         <title>Hello Phoenix!</title>
         <link rel="stylesheet" href="<%= static_path(@conn, "/css/bootstrap.css") %>">
         <link rel="stylesheet" href="<%= static_path(@conn, "/css/login.css") %>">
         <link rel="stylesheet" href="<%= static_path(@conn, "/js/bootstrap.js") %>">
       </head>
    
       <body>
         <%= @inner %>
       </body>
     </html>
    

    2) hello_phoenix/web/templates/page/index.html.eex 를 아래와 같이 수정합니다.
     <div class="container">
         <div class="row">
             <div class="col-sm-6 col-md-4 col-md-offset-4">
                 <div class="account-wall">
                   <form class="form-signin" action="<%= page_path(@conn, :login) %>" method="post">
                     <input type="text" class="form-control" name="user[email]" placeholder="Email" required autofocus>
                     <input type="password" class="form-control" name="user[password]" placeholder="Password" required>
                     <input type="hidden" name="_csrf_token" value="<%= get_csrf_token() %>">
                     <button class="btn btn-lg btn-primary btn-block" type="submit">
                         Sign in</button>
                     <label class="checkbox pull-left">
                         <input type="checkbox" value="remember-me">
                         Remember me
                     </label>
                     <a href="#" class="pull-right need-help">Need help? </a><span class="clearfix"></span>
                     </form>
                 </div>
                 <a href="#" class="text-center new-account">Create an account </a>
             </div>
         </div>
     </div>
    

    <input type="hidden" name="_csrf_token" value="<%= get_csrf_token() %>"> 를 넣고 있을까는 stackoverflow 질문 를 참조하면 됩니다. 이 한 줄을 넣지 않으면 아래와 같은 오류가 발생합니다.invalid CSRF (Cross Site Forgery Protection) token, make sure all requests include a '_csrf_token' param or an 'x-csrf-token' header


    3) login.css 파일을 아래 내용으로 만들고 hello_phoenix/priv/static/css/ 디렉토리 아래로 이동합니다.
    .form-signin
    {
        max-width: 330px;
        padding: 15px;
        margin: 0 auto;
    }
    .form-signin .form-signin-heading, .form-signin .checkbox
    {
        margin-bottom: 10px;
    }
    .form-signin .checkbox
    {
        font-weight: normal;
    }
    .form-signin .form-control
    {
        position: relative;
        font-size: 16px;
        height: auto;
        padding: 10px;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    .form-signin .form-control:focus
    {
        z-index: 2;
    }
    .form-signin input[type="text"]
    {
        margin-bottom: -1px;
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
    }
    .form-signin input[type="password"]
    {
        margin-bottom: 10px;
        border-top-left-radius: 0;
        border-top-right-radius: 0;
    }
    .account-wall
    {
        margin-top: 20px;
        padding: 40px 0px 20px 0px;
        background-color: #f7f7f7;
        -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
        -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
        box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    }
    .login-title
    {
        color: #555;
        font-size: 18px;
        font-weight: 400;
        display: block;
    }
    .profile-img
    {
        width: 96px;
        height: 96px;
        margin: 0 auto 10px;
        display: block;
        -moz-border-radius: 50%;
        -webkit-border-radius: 50%;
        border-radius: 50%;
    }
    .need-help
    {
        margin-top: 10px;
    }
    .new-account
    {
        display: block;
        margin-top: 10px;
    }
    

    4) hello_phoenix/web/router.ex 파일에 /login 부분을 추가하여 아래와 같이됩니다. 주의하고 싶은 것은 post 를 사용하고 있습니다.
     defmodule HelloPhoenix.Router do
       use HelloPhoenix.Web, :router
    
       pipeline :browser do
         plug :accepts, ["html"]
         plug :fetch_session
         plug :fetch_flash
         plug :protect_from_forgery
       end
    
       pipeline :api do
         plug :accepts, ["json"]
       end
    
       scope "/", HelloPhoenix do
         pipe_through :browser # Use the default browser stack
    
         get "/", PageController, :index
         post "/login", PageController, :login
         resources "/users", UserController
       end
     end
    
    

    5) 이제 앱을 시작하여 로그인 페이지가 표시됩니다.
    14:28:36 [N1210A001 => ~/Playground/elixir/hello_phoenix]
    $ mix phoenix.server
    


  • 이제 로그인 프로세스로 들어갑니다. hello_phoenix/web/controllers/page_controller.ex 파일을 다음과 같이 수정하십시오.
  •  defmodule HelloPhoenix.PageController do
       use HelloPhoenix.Web, :controller
    
       # `query = from u in User,`部分
       # の`User`が使える為にaliasしている
    
       alias HelloPhoenix.User
    
       # `redirect conn, to: Helpers.user_path(conn, :index)`部分
       # の`Helpers.user_path`が使えるためにaliasをしている
    
       alias HelloPhoenix.Router.Helpers
    
       plug :action
    
       def index(conn, _params) do
         render conn, "index.html"
       end
    
       def login(conn, %{"user" => %{"email" => email, "password" => password}}) do
         query = from u in User,
                   where: u.email == ^email,
                   where: u.password == ^password,
                   select: u.id
         result = HelloPhoenix.Repo.all(query)
         # ユーザーが存在すればユーザー一覧ページにリダイレクトされます
         case length(result) > 0 do
           true ->
             redirect conn, to: Helpers.user_path(conn, :index)
           false ->
             text conn, "ログイン失敗"
         end
       end
     end
    

    이제 가장 간단한 로그인 페이지를 만들었습니다. 또한 구현하지 않은 부분은

    1) 암호 암호화
    2) 로그인하지 않은 사용자는 사용자 목록을 볼 수 없도록

    누군가 위와 같은 기능을 구현하면 알려주세요. 특히 2)번째입니다.

    좋은 웹페이지 즐겨찾기