{"size": 2045, "ext": "js", "max_stars_repo_path": "client.js", "max_stars_repo_name": "bogdan-karlenko/auth0-unnr", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "client.js", "max_issues_repo_name": "bogdan-karlenko/auth0-unnr", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client.js", "max_forks_repo_name": "bogdan-karlenko/auth0-unnr", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.9892473118, "max_line_length": 65, "alphanum_fraction": 0.666992665}
const url = require("url")
const express = require("express")
const bodyParser = require("body-parser")
const axios = require("axios").default
const { randomString, timeout } = require("./utils")

const config = {
	port: 9000,

	clientId: "my-client",
	clientSecret: "zETqHgl0d7ThysUqPnaFuLOmG1E=",
	redirectUri: "http://localhost:9000/callback",

	authorizationEndpoint: "http://localhost:9001/authorize",
	tokenEndpoint: "http://localhost:9001/token",
	userInfoEndpoint: "http://localhost:9002/user-info",
}
let state = ""

const app = express()
app.set("view engine", "ejs")
app.set("views", "assets/client")
app.use(timeout)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get("/authorize", (req, res) => {
	state = randomString()
	const redirectUrl = url.parse(config.authorizationEndpoint)
	redirectUrl.query = {
		response_type: "code",
		client_id: config.clientId,
		redirect_uri: config.redirectUri,
		scope: "permission:name permission:date_of_birth",
		state: state,
	}
	res.redirect(url.format(redirectUrl))
})

app.get("/callback", (req, res) => {
	if (req.query.state !== state) {
		res.status(403).send("Error: state mismatch")
		return
	}
	const { code } = req.query
	axios({
		method: "POST",
		url: config.tokenEndpoint,
		auth: {
			username: config.clientId,
			password: config.clientSecret,
		},
		data: {
			code,
		},
		validateStatus: null,
	})
		.then((response) => {
			return axios({
				method: "GET",
				url: config.userInfoEndpoint,
				headers: {
					authorization: "bearer " + response.data.access_token,
				},
			})
		})
		.then((response) => {
			res.render("welcome", { user: response.data })
		})
		.catch((err) => {
			console.error(err)
			res.status(500).send("Error: something went wrong")
		})
})

const server = app.listen(config.port, "localhost", function () {
	var host = server.address().address
	var port = server.address().port
})

// for testing purposes

module.exports = {
	app,
	server,
	getState() {
		return state
	},
	setState(s) {
		state = s
	},
}
