더북(TheBook)

로그인할 때 하는 작업은 다음과 같다.

1. username으로 사용자 조회

2. bcrypt 패키지의 CompareHashAndPassword 함수로 패스워드 비교

패스워드 비교는 bcrypt 방식을 사용했다. bcrypt 방식은 패스워드를 저장할 목적으로 설계된 강력한 해시 메커니즘 중 하나이다. bcrypt 패키지를 사용하려면 먼저 go get golang.org/x/crypto/bcrypt 명령으로 패키지를 내려받아야 한다.

명령 프롬프트

$ go get golang.org/x/crypto/bcrypt

3. 패스워드가 일치하면 세션 생성 후 포스트 목록 화면으로 이동

사용자 확인이 완료되면 revel.Sign 함수로 authKey를 생성하고(authKey := revel.Sign(user.Username)), authKeyusername과 함께 세션에 저장한다. authKeyusername은 사용자를 인증할 때 사용된다.

4. 패스워드가 일치하지 않으면 세션 정보를 모두 제거하고 홈으로 이동

패스워드로 사용자를 확인한 후 authKey를 생성하는 데 revel.Sign 함수를 사용하고, 이후에 authKey를 확인하는 작업은 Verify 함수를 사용한다. Sign 함수와 Verify 함수는 다음과 같다(https://github.com/revel/revel/blob/master/libs.go 참고).

▼ revel의 Sign 함수 & Verify 함수

// Sign a given string with the app-configured secret key.
// If no secret key is set, returns the empty string.
// Return the signature in base64 (URLEncoding).
func Sign(message string) string {
    if len(secretKey) == 0 {
        return ””
    }
    mac := hmac.New(sha1.New, secretKey)
    io.WriteString(mac, message)
    return hex.EncodeToString(mac.Sum(nil))
}
 
// Verify returns true if the given signature is correct for the given message.
// e.g. it matches what we generate with Sign()
func Verify(message, sig string) bool {
    return hmac.Equal([]byte(sig), []byte(Sign(message)))
}

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