기본 콘텐츠로 건너뛰기

meteor 에서 E-mail 인증하기


MAIL_URL은 gmail을 쓸 경우 다음과 같이 설정하면 된다.

smtp://사용자계정%40gmail.com:계정암호@smtp.gmail.com:465/

혹은 google apps 계정은 경우

smtp://사용자계정%40구글Apps도메인:계정암호@smtp.gmail.com:465/

----
가입자 확인 메일 발송엔 몇가지 문제가 있는데
1. Text로 메일을 보낸다.
2. Formatted 형식을 사용할 수 없다.

이건 내가 생각해봐도 좀 아니다 싶다.
server 쪽에서 startup 할때 기존 Accounts.emailTemplate과 Accounts.sendVerificationEmail 등등이 제대로 작동하도록 바꿔치기 해주자.

:: email.coffee

Meteor.startup ->
  # set Mail configuration
  Email = Package.email.Email;

  _.extend Accounts.emailTemplates,
    from: "Gearlounge <no-reply@gearlounge.com>"
    verifyEmail:
      subject: (user)->
        "#{"#{user.profile.displayName}님, "if (user.profile and user.profile.displayName)?}가입을 환영합니다."
      html: (user, url)->
        Handlebars.templates['verifyEmail'](
          user: user.profile && user.profile.displayName
          verifyEmailUrl: url
          urlHome: Meteor.absoluteUrl()
        )
  # hack for handlebars-server
  _.extend Accounts.sendVerificationEmail = (userId, address) ->
    user = Meteor.users.findOne userId
    throw new Error "Can't find user" if not user?
    if not address?
      email = _.find user.emails || [], (e) -> !e.verified
      address = (email || {}).address

    throw new Error "No such email address for user." if not address or not _.contains(_.pluck(user.emails || [], 'address'), address)

    tokenRecord =
      token: Random.id()
      address: address
      when: new Date()
    Meteor.users.update
      _id: userId
    ,
      $push:
        "services.email.verificationTokens": tokenRecord
    verifyEmailUrl = Accounts.urls.verifyEmail tokenRecord.token
    Email.send
      to: address
      from: Accounts.emailTemplates.from
      subject: Accounts.emailTemplates.verifyEmail.subject user
      html: Accounts.emailTemplates.verifyEmail.html user, verifyEmailUrl
    return

위 코드는 기존 accounts-password.js의 Accounts.emailTemplates을 그대로 옮겨(물론 coffeescript로 바꾸긴 했지만) 놓은 수준이다.
하지만 노랑색으로 그어 놓은 부분이 변경한 부분인데 기존 Accounts.emailTemplates는 text밖에 사용할 수 없어서 html을 인자로 주었고 메일 양식도 하드코딩된 부분을 handlebars-server(https://github.com/EventedMind/meteor-handlebars-server) 패키지를 사용하여 양식화하였다.

      html: (user, url)->
        Handlebars.templates['verifyEmail'](
          user: user.profile && user.profile.displayName
          verifyEmailUrl: url
          urlHome: Meteor.absoluteUrl()
        )

위 코드에서 보듯 verifyEmail 이란 template 을 사용하는데 server쪽 디렉토리 아래 적당히 verifyEmail.handlebars 라는 파일을 생성하면 알아서 잘 찾는다.
은근 괜찮음 추천추천.

서버사이드 핸들바도 클라이언트처럼 쓰면 된다. user, verifyEmailUrl, urlHome 을 각각 인자로 사용하는데 이 세개를 handlebars에서도 똑같이 이용한다.

<div>
<img src="{{urlHome}}image/header.img">
</div>
<p>
  안녕하세요. {{user}}님. 가입을 환영합니다.
</p>
<p>
  사용자 확인을 위해 아래 링크를 클릭해주세요.
</p>
<p>
  <a href="{{verifyEmailUrl}}" target="_blank">{{verifyEmailUrl}}</a>
</p>

이렇게 구성하면 오케이.
아마 verifyEmailUrl 은 아마도 http://localhost:3000/#/verify-email/HmfLCxjRKoRreqKWW 이런 형태일텐데

이제 이 경로로 오면 실제로 처리해주는 걸 만들어주면 되겠다.
클라이언트로 /verify-email/<token> 의 URL요청이 들어오면 처리하면 될텐데
내 경우엔 meteor-router(https://github.com/tmeasday/meteor-router) 패키지를 사용하므로
아래와 같이 구현했다.

Meteor.Router.add
....
  '/verify-email/:token':(token)->
    result = Meteor.call 'confirmEmail', token
    'confirmMail'

token을 인자로 'confirmEmail' method를 호출하면 해당계정의 email의 verified가 true가 되면서 사용가능한 상태로 만들 수 있다. 그리고 confirmMail 템플릿으로 포워딩하는 것으로 마무리.
만일 싱글페이지 앱이라면 url 분석해서 처리하는 방법도 있겠다.

물론 인증이 필요한 부분에 필터링을 한다던가 하는 세세한 부분의 구현이 있지만 실제로 해보면서 확인해보자.

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.org 를