riot-translatebot

A simple riot bot which provides Status about Weblate
git clone git://archive.git.mtrnord.blog/Nordgedanken/riot-translatebot.git
Log | Files | Refs | README | LICENSE

login.js (1724B)


      1 import matrix_sdk from 'matrix-js-sdk';
      2 import fs from 'mz/fs';
      3 import node_fs from 'fs';
      4 
      5 import config from '../config.json';
      6 
      7 export default class Login {
      8     constructor() {};
      9     getClient = () => {
     10         return this.login();
     11     };
     12 
     13     login = () => {
     14         if (node_fs.existsSync('user_data.json')){
     15             const json = node_fs.readFileSync('user_data.json');
     16             const valid_json = JSON.parse(json);
     17             if (valid_json.hasOwnProperty("access_token")){
     18                 return this.useToken(valid_json["access_token"], valid_json["user_id"], valid_json["home_server"]);
     19             } else {
     20                 return this.usePassword();
     21             }
     22         } else {
     23             return this.usePassword();
     24         }
     25     };
     26 
     27     usePassword = () => {
     28         const matrixClient = matrix_sdk.createClient({
     29             baseUrl: "https://matrix.org",
     30             userId: config["username"]
     31         });
     32 
     33         matrixClient.loginWithPassword(config["username"], config["password"]).then( data => {
     34             console.log(data);
     35             fs.writeFile('user_data.json', JSON.stringify(data), 'utf8')
     36             .then(() => {
     37                 console.log("saved Access_token to file");
     38             })
     39             .catch(err => {
     40                 console.error(err);
     41             })
     42         });
     43         return new Promise(resolve => {
     44             resolve(matrixClient);
     45         });
     46     };
     47 
     48     useToken = (token, userId, baseUrl) => {
     49         const matrixClient = matrix_sdk.createClient({
     50             baseUrl: "https://" + baseUrl,
     51             userId: userId,
     52             accessToken: token
     53         });
     54         return new Promise(resolve => {
     55             resolve(matrixClient);
     56         });
     57     };
     58 }