상세 컨텐츠

본문 제목

How to sign in and sign up with Firebase on Javascript

Go

by 경밤 2020. 4. 25. 19:19

본문

반응형

Before reading this post, you have to set up all settings for firebase.

You can find documentations at here, and you have to build a simple localhost server. I think this would help you.

Let's go to build simple login/logout/register code.

Registing will be handled on Firebase admin SDK (on server) and the elses will be handled on Web.

First, You have to add this code snippets in your html files which you want to do something with firebase on js because js always depends on html. included firebase scripts and your own javascript are always related.

<script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script>

<script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-auth.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js"></script>
<script src="/js/firebase-init.js" defer></script>

So now, we are going to make initializing code for firebase. As you saw the code above, we already added firebase-init.js. 

firebase-init.js

// Your web app's Firebase configuration
var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

It's all you can find the configuration at your firebase project's settings tab.

Second, build index page.

index.js conduct check logined and do logout. index.js check the current state of user and handle.

if the user logined then display user information and logout button, if not, display login button.

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/css/index.css">
</head>

<body>
    <div class="navigation">
        <div class="navigation-left">
            <a href="/">Home</a>
        </div>
        <div class="navigation-right">
            <a href="/">Account</a>
            <a href="/">Information</a>
            <div id="user-section">
                <a href="/" id="user-section-displayname"></a>
                <a id="logout-btn">LogOut</a>
            </div>

            <a href="/login" id="login-btn">Login</a>
        </div>
    </div>

    <script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script>

    <script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-auth.js"></script>
    <script defer src="https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js"></script>
    <script src="../js/firebase-init.js" defer></script>
    <script src="../js/index.js" defer></script>
</body>

</html>

index.css

@font-face {
    font-family: 'NotoSerifKR';
    src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_two@1.0/NotoSerifKR.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

body {
    margin: 0;
    font-family: 'NotoSerifKR';
    background-color: #333333;
}

.navigation {
    width: 700px;
    overflow: hidden;
    margin: auto;
}

.navigation a {
    display: block;
    color: rgb(255, 255, 255);
    text-align: center;
    float: left;
    text-decoration: none;
    padding: 15px;
    font-size: 1.2em;
}

.navigation .navigation-right {
    float: right;
}

.navigation a:hover {
    border-radius: 10px 10px 0px 0px;
    background-color: rgba(255, 17, 0, 0.774);
}

#login-btn {
    display: none;
}

#user-section {
    display: none;
}

index.js

let userSection = document.getElementById("user-section");
let loginBtn = document.getElementById("login-btn")

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        userSection.style.display = "inline"
        document.getElementById("user-section-displayname").innerText = user.displayName
    } else {
        loginBtn.style.display = "inline"
    }
});

document.getElementById("logout-btn").addEventListener("click", () => {
    firebase.auth().signOut().then(function() {
        location.href = "/"
    }).catch(function(error) {
        alert("Unexcepted Error occur")
    });
})

We can check login or not to use onAuthStateChanged. 

Third, we are going to make a login page but it depends on your thought. so I will show only javascript code.

login.js

//If login succeed, then redirect to index page
firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        location.href = "/"
    }
});

document.getElementById("login_btn").addEventListener("click", (event) => {
    
    //Get the email and password at your html code
    email = document.getElementById("email")
    password = document.getElementById("password")
    
    //Create session
    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
        .then(function() {
        	//return your sign in function (you can enable the ways to sign in at your firebase)
            return firebase.auth().signInWithEmailAndPassword(email.value, password.value).catch((error) => {
                //Error handling
            });
        })
        .catch(function(error) {
            // Handle Errors set Persistence
        });

})

Yea, we made index page and login page. next we need build server code but, in this post I wouldn't like to build whole server code. So you may need more informations for SignUp user. then this would help you.

handling register request.

func RegisterHandler(c echo.Context) error {
	params := (&auth.UserToCreate{}).
		Email(c.FormValue("email")).
		EmailVerified(false).
		Password(c.FormValue("password")).
		DisplayName(c.FormValue("name")).
		Disabled(false)

	_, err := client.CreateUser(context.Background(), params)
	if err != nil {
		if auth.IsEmailAlreadyExists(err) {
			return c.Render(http.StatusOK, "result.html", map[string]interface{}{
				"title": "Sign Up failed",
				"body":  "Email has been Already Exists",
			})
		}
		return c.Render(http.StatusOK, "result.html", map[string]interface{}{
			"title": "Sign Up failed",
			"body":  err.Error(),
		})
	}
	return c.Render(http.StatusOK, "result.html", map[string]interface{}{
		"title": "Sign Up SUCCEED",
		"body":  "<a href='/'>--> GO BACK <--</a>",
	})
}

I repeat, You can follow this post to build a simple golang server.

 

Thank you byebye

반응형

관련글 더보기