1<?php
2
3if(!defined('DOKU_INC')) die();
4require_once(dirname(__FILE__).'/GoogleAuthenticator.php');
5
6class TokenHelper {
7
8    protected $_g2fafile = "";
9
10    public function TokenHelper() {
11        global $conf;
12
13        $this->_g2fafile = $conf['metadir'].'/g2fa_secrets.php';
14    }
15
16    public function getTokens() {
17        $ret = array();
18
19        if(!@file_exists($this->_g2fafile))
20            return $ret;
21
22        $lines = file($this->_g2fafile);
23        foreach($lines as $line) {
24            $line = preg_replace('/#.*$/', '', $line); //ignore comments
25            $line = trim($line);
26            if(empty($line)) continue;
27
28            $row    = explode(":", $line, 2);
29            $user = $row[0];
30            $secret = $row[1];
31            $ret[$user] = $secret;
32        }
33        return $ret;
34    }
35
36    public function saveToken($user, $token)
37    {
38        $content = $user.":".$token."\n";
39
40        if(!io_deleteFromFile($this->_g2fafile, '/^'.preg_quote($user).':/', true)) {
41            msg('Unable to modify content data. Notify the Admin!');
42            return false;
43        }
44
45        if(!@file_exists($this->_g2fafile)) {
46            $header = "# g2fa_secrets.php\n# <?php exit()?>\n# Don't modify the lines above";
47            $header .= "#\n# Userfile\n#\n# Format:\n#\n# login:secret\n\n";
48            if(!io_saveFile($this->_g2fafile, $header, false)) {
49              msg('There was an error saving to the file. Notify the Admin!');
50              return false;
51            }
52        }
53
54
55        if(!io_saveFile($this->_g2fafile, $content, true)) {
56            msg('There was an error saving to the file. Notify the Admin!');
57            return false;
58        }
59
60        return true;
61    }
62
63    public function deleteTokenForUser($user) {
64        if(!io_deleteFromFile($this->_g2fafile, '/^'.preg_quote($user).':/', true)) {
65           msg('Unable to modify the content data. Notify the Admin!');
66           return false;
67        }
68        return true;
69    }
70
71    public function createTokenForUser($user) {
72        $ga = new PHPGangsta_GoogleAuthenticator();
73        $token = $ga->createSecret();
74        return $this->saveToken($user, $token);
75    }
76
77    function getSecret($user) {
78        $tokens = $this->getTokens();
79        if(isset($tokens[$user]))
80          return $tokens[$user];
81        else
82          return "";
83
84    }
85
86}
87