summaryrefslogtreecommitdiff
path: root/public/js/auth.js
blob: e16c2d26c0a47237202331cdb56ee3ee02ea5e0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var Auth =
	{
	name: '',
	userID: 1,
	isHost: false,
	loginPrompt: false,
	hosts: {},
	init: function () {
		$.post(URL.auth.login, {}, Auth.loginCallback)
	},
	unload: function () {
		if (Auth.loginPrompt) {
			Auth.loginPrompt = false
			$('#login').fadeOut(1000, function(){ Main.load()} )
		}
		else {
			Main.load()
		}
	},
	load: function () {
		$('#login').fadeIn(1000)
		$('#login-email').focus()
		$('#login-email').keydown(Main.kp)
		$('#login-password').keydown(Main.kp)
		$('#login-go').click( Auth.login )
		Auth.loginPrompt = true
		Main.saveFunction = Auth.login
		Main.saving = false
	},
	login: function () {
		if (Main.saving)
			return
		Main.saving = true
		warn("attempting login")
		var data = {
			username: $('#login-email').val(),
			password: $('#login-password').val(),
		}
		$('#login-password').val(''),
		$.post(URL.auth.login, data, Auth.loginCallback)
	},
	loginCallback: function (json) {
		Main.saving = false

		if (! json || json.error) {
			if (! Auth.loginPrompt)
				Auth.load()
			else
				warn("bad login!")
			return
		}

		// 0 id  1 name  2 firstname  3 email  4 access
		var user = Auth.user = json.user

		var name = user.name.split(' ')[0] || user.email.split('@')[0]
		warn( "Logged in! Hello "+name )
		Auth.userID = user.id
		Auth.isHost = user.access == 2 ? true : false;
		Auth.name = user.name
		Auth.firstName = name

		$('#profile-edit').html(Auth.firstName + "!")
		$('#logout').click( Auth.logout )

		var hostSelect = ""
		Auth.hosts = {}
		json.hosts.forEach(function(host){
			if (host.id === Auth.userID)
				hostSelect += "<option value='"+host.id+"' selected='1'>"+host.name+"</option>"
			else
				hostSelect += "<option value='"+host.id+"'>"+host.name+"</option>"
			Auth.hosts[ host.id ] = host.name
		})

		$("#user-host").html(hostSelect)
		
		Auth.unload()
		},
	logout: function ()
		{
		warn("logging out")
		$('#login-email').val(''),
		$.get(URL.auth.logout,{}, function(){
			Main.unload()
		})
		},
	};