<commit_before>import decodeToken from 'jwt-decode'
import ajax from '../utils/ajax'
import config from '../config.js'

let hasLocalStorage = true

// Test localStorage
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
try {
    localStorage.setItem('t', 't')
    localStorage.removeItem('t')
} catch (e) {
    hasLocalStorage = false
    alert('Seu navegador parece não suportar localStorage. Por favor use um mais recente, ou você não conseguirá autenticar nesse site...')
}

// This code is needed to restore the hash after a redirect for login
// through a third-party.
// If redicected for login (from Facebook)
if (/^\?redirect_state=/.test(location.search)) {
    var url = location.origin + "/" + localStorage.prevhash
    // Save info to get tokens after page load/reload
    // If History is supported, tokens should be loaded after page load.
    // If History isn't supported, tokens should be loaded after page reload.
    localStorage.queryForToken = location.search
    if (window.history.replaceState) {
        window.history.replaceState(null, null, url)
    } else {
        // Fallback method that doesn't requires "window.history" but
        // reloads the page.
        location.href = url
    }
}


class Auth {
    constructor(signal) {
        riot.observable(this)

        // The page was reloaded and a getToken is pending.
        // Needed when browser has no support for window.history
        if (localStorage.queryForToken) {
            this.completeFacebook(localStorage.queryForToken)
            localStorage.queryForToken = ""
        }

        console.log('register-event')
        this.on(riot.VEC('register'), params => this.register(params))
        this.on(riot.VEC('login'), params => this.login(params))
        this.on(riot.VEC('loginFacebook'), () => this.loginFacebook())
        this.on(riot.VEC('logout'), () => this.logout())
        // View requesting current username
        this.on(riot.VEL('username'), () => {
            this.trigger(riot.SEC('username'), this.getUsername())
        })
        riot.control.addStore(this)
    }

    saveTokens(response) {
        // document.cookie = "token=" + data.token
        localStorage.mainToken = response.json.mainToken
        this.saveMicroToken(response.json)
        this.username = this.getUsername()
        this.trigger(riot.SEC('username'), this.username)
    }

    saveMicroToken(data) {
        console.log("SAVE", data)
        localStorage.microToken = data.microToken

        var now = new Date()
        // Convert valid period from minutes to miliseconds, add it to now and
        // save for future checks, to see if it's still valid. We use this value
        // for checks instead of the exp field in the tokens because server and
        // clients may differ time settings.
        localStorage.microTokenValidTime = now.getTime() + data.microTokenValidPeriod * 60000
    }

    getUsername() {
        if (localStorage.mainToken) {
            try {
                return decodeToken(localStorage.mainToken).username
            } catch(err) {
                localStorage.removeItem("mainToken")
                localStorage.removeItem("microToken")
                alert("Error to decode stored token! Please relogin...")
            }
        }
        return null
    }

    register(params) {
        ajax({
            url: config.apiurl_auth + "/user/" + params.username,
            data: {password: <PASSWORD>, email: params.email},<commit_msg>async func to return/renew micro token<commit_after>import decodeToken from 'jwt-decode'
import ajax from '../utils/ajax'
import config from '../config.js'

let hasLocalStorage = true

// Test localStorage
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
try {
    localStorage.setItem('t', 't')
    localStorage.removeItem('t')
} catch (e) {
    hasLocalStorage = false
    alert('Seu navegador parece não suportar localStorage. Por favor use um mais recente, ou você não conseguirá autenticar nesse site...')
}

// This code is needed to restore the hash after a redirect for login
// through a third-party.
// If redicected for login (from Facebook)
if (/^\?redirect_state=/.test(location.search)) {
    var url = location.origin + "/" + localStorage.prevhash
    // Save info to get tokens after page load/reload
    // If History is supported, tokens should be loaded after page load.
    // If History isn't supported, tokens should be loaded after page reload.
    localStorage.queryForToken = location.search
    if (window.history.replaceState) {
        window.history.replaceState(null, null, url)
    } else {
        // Fallback method that doesn't requires "window.history" but
        // reloads the page.
        location.href = url
    }
}

class Auth {
    constructor(signal) {
        riot.observable(this)

        // The page was reloaded and a getToken is pending.
        // Needed when browser has no support for window.history
        if (localStorage.queryForToken) {
            this.completeFacebook(localStorage.queryForToken)
            localStorage.queryForToken = ""
        }

        console.log('register-event')
        this.on(riot.VEC('register'), params => this.register(params))
        this.on(riot.VEC('login'), params => this.login(params))
        this.on(riot.VEC('loginFacebook'), () => this.loginFacebook())
        this.on(riot.VEC('logout'), () => this.logout())
        // View requesting current username
        this.on(riot.VEL('username'), () => {
            this.trigger(riot.SEC('username'), this.getUsername())
        })
        riot.control.addStore(this)
    }

    saveTokens(response) {
        // document.cookie = "token=" + data.token
        localStorage.mainToken = response.json.mainToken
        this.saveMicroToken(response.json)
        this.username = this.getUsername()
        this.trigger(riot.SEC('username'), this.username)
    }

    saveMicroToken(data) {
        console.log("SAVE", data)
        localStorage.microToken = data.microToken

        var now = new Date()
        // Convert valid period from minutes to miliseconds, add it to now and
        // save for future checks, to see if it's still valid. We use this value
        // for checks instead of the exp field in the tokens because server and
        // clients may differ time settings.
        localStorage.microTokenValidTime = now.getTime() + data.microTokenValidPeriod * 60000
    }

    async getMicroToken() {
        var now = new Date()

        // Check if micro token is still valid for 30s
        if (now < localStorage.microTokenValidTime - 30000) {
            console.log('auth:getMicroToken: no need to renew token')
        } else {
            let url = config.apiurl_auth + "/renew_micro_token",
                data = {
                    'token': localStorage.mainToken
                }
            console.log('auth:getMicroToken: renewing token with:', data)
            data = await ajax({url, data, method: 'post'})
            this.saveMicroToken(data.json)
        }
        return localStorage.microToken
    }

    getUsername() {
        if (localStorage.mainToken) {
            try {
                return decodeToken(localStorage.mainToken).username
            } catch(err) {
                localStorage.removeItem("mainToken")
                localStorage.removeItem("microToken")
                alert("Error to decode stored token! Please relogin...")
            }
        }
        return null
    }

    register(params) {
        ajax({
            url: config.apiurl_auth + "/user/" + params.username,
            data: {password: <PASSWORD>, email: params.email},
{'fraction_non_alphanumeric': 0.11122607346094154, 'fraction_numerical': 0.002198654940506984, 'mean_word_length': 2.3694989106753814, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7441337', 'n_tokens_mistral': 2190, 'n_tokens_neox': 2073, 'n_words': 579}