1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-24 10:27:10 +02:00

Login screen

This commit is contained in:
Laurent Cozic 2017-05-14 23:51:45 +02:00
parent bc8fdf582a
commit e4c0345f4b
12 changed files with 103 additions and 54 deletions

View File

@ -1,7 +1,7 @@
import { Log } from 'src/log.js';
import { Database } from 'src/database.js';
import { Registry } from 'src/registry.js';
import createUuid from 'uuid/v4';
import { uuid } from 'src/uuid.js';
class BaseModel {
@ -18,7 +18,7 @@ class BaseModel {
let query = '';
if (isNew) {
if (this.useUuid()) o.id = createUuid();
if (this.useUuid()) o.id = uuid.create();
query = Database.insertQuery(this.tableName(), o);
} else {
let where = { id: o.id };

View File

@ -1,7 +1,11 @@
import { Registry } from 'src/registry.js';
class BaseService {
constructor(webApi) {
this.api_ = webApi;
constructor() {}
api() {
return Registry.api();
}
}

View File

@ -1,7 +1,10 @@
import React, { Component } from 'react';
import { View, Button, TextInput } from 'react-native';
import { View, Button, TextInput, Text } from 'react-native';
import { connect } from 'react-redux'
import { Log } from 'src/log.js'
import { Registry } from 'src/registry.js';
import { Setting } from 'src/models/setting.js';
import { _ } from 'src/locale.js';
class LoginScreenComponent extends React.Component {
@ -11,11 +14,15 @@ class LoginScreenComponent extends React.Component {
constructor() {
super();
this.state = { username: '', password: '' };
this.state = {
email: '',
password: '',
errorMessage: null,
};
}
username_changeText = (text) => {
this.setState({ username: text });
email_changeText = (text) => {
this.setState({ email: text });
}
password_changeText = (text) => {
@ -23,22 +30,26 @@ class LoginScreenComponent extends React.Component {
}
loginButton_press = () => {
Log.info('LOGIN');
// Note.save(this.state.note).then((note) => {
// this.props.dispatch({
// type: 'NOTES_UPDATE_ONE',
// note: note,
// });
// }).catch((error) => {
// Log.warn('Cannot save note', error);
// });
this.setState({ errorMessage: null });
return Registry.api().post('sessions', null, {
'email': this.state.email,
'password': this.state.password,
'client_id': Setting.value('clientId'),
}).then((session) => {
Log.info('GOT DATA:');
Log.info(session);
}).catch((error) => {
this.setState({ errorMessage: _('Could not login: %s)', error.message) });
});
}
render() {
return (
<View style={{flex: 1}}>
<TextInput value={this.state.username} onChangeText={this.username_changeText} />
<TextInput value={this.state.password} onChangeText={this.password_changeText} />
<TextInput value={this.state.email} onChangeText={this.email_changeText} keyboardType="email-address" />
<TextInput value={this.state.password} onChangeText={this.password_changeText} secureTextEntry={true} />
{ this.state.errorMessage && <Text style={{color:'#ff0000'}}>{this.state.errorMessage}</Text> }
<Button title="Login" onPress={this.loginButton_press} />
</View>
);

View File

@ -1,6 +1,6 @@
import SQLite from 'react-native-sqlite-storage';
import { Log } from 'src/log.js';
import createUuid from 'uuid/v4';
import { uuid } from 'src/uuid.js';
const structureSql = `
CREATE TABLE folders (
@ -102,7 +102,7 @@ class Database {
}
open() {
this.db_ = SQLite.openDatabase({ name: '/storage/emulated/0/Download/joplin-4.sqlite' }, (db) => {
this.db_ = SQLite.openDatabase({ name: '/storage/emulated/0/Download/joplin-5.sqlite' }, (db) => {
Log.info('Database was open successfully');
}, (error) => {
Log.error('Cannot open database: ', error);
@ -156,13 +156,7 @@ class Database {
selectAll(sql, params = null) {
this.logQuery(sql, params);
return new Promise((resolve, reject) => {
this.db_.executeSql(sql, params, (r) => {
resolve(r);
}, (error) => {
reject(error);
});
});
return this.exec(sql, params);
}
exec(sql, params = null) {
@ -170,7 +164,7 @@ class Database {
return new Promise((resolve, reject) => {
this.db_.executeSql(sql, params, (r) => {
resolve();
resolve(r);
}, (error) => {
reject(error);
});
@ -236,13 +230,12 @@ class Database {
Log.info('Database is new - creating the schema...');
let statements = this.sqlStringToLines(structureSql)
//this.db_.transaction((tx) => {
this.transaction((tx) => {
try {
for (let i = 0; i < statements.length; i++) {
tx.executeSql(statements[i]);
}
tx.executeSql('INSERT INTO settings (`key`, `value`, `type`) VALUES ("clientId", "' + createUuid() + '", "' + Database.enumToId('settings', 'string') + '")');
tx.executeSql('INSERT INTO settings (`key`, `value`, `type`) VALUES ("clientId", "' + uuid.create() + '", "' + Database.enumToId('settings', 'string') + '")');
} catch (error) {
reject(error);
}

View File

@ -1,7 +1,9 @@
import { sprintf } from 'sprintf-js';
// This function does nothing for now, but later will return
// a different string depending on the language.
function _(s) {
return s;
function _(s, ...args) {
return sprintf(s, ...args);
}
export { _ };

View File

@ -2,22 +2,39 @@
class Log {
static setLevel(v) {
this.level_ = v;
}
static level() {
return this.level_ === undefined ? Log.LEVEL_ERROR : this.level_;
}
static debug(...o) {
if (Log.level() > Log.LEVEL_DEBUG) return;
console.debug(...o);
}
static info(...o) {
if (Log.level() > Log.LEVEL_INFO) return;
console.info(...o);
}
static warn(...o) {
if (Log.level() > Log.LEVEL_WARN) return;
console.info(...o);
}
static error(...o) {
if (Log.level() > Log.LEVEL_ERROR) return;
console.info(...o);
}
}
Log.LEVEL_DEBUG = 0;
Log.LEVEL_INFO = 10;
Log.LEVEL_WARN = 20;
Log.LEVEL_ERROR = 30;
export { Log };

View File

@ -14,6 +14,7 @@ import { Registry } from 'src/registry.js';
function main() {
Registry.setDebugMode(true);
AppRegistry.registerComponent('AwesomeProject', () => Root);
Log.setLevel(Registry.debugMode() ? Log.LEVEL_DEBUG : Log.LEVEL_WARN);
// Note: The final part of the initialization process is in
// AppComponent.componentDidMount(), when the application is ready.
}

View File

@ -5,6 +5,7 @@
// dependency injection later on (eg. `BaseModel.db()`, `Synchroniser.api()`)
import { Database } from 'src/database.js'
import { WebApi } from 'src/web-api.js'
class Registry {
@ -17,8 +18,10 @@ class Registry {
return this.debugMode_;
}
static setApi(v) {
this.api_ = v;
static api() {
if (this.api_) return this.api_;
this.api_ = new WebApi('http://192.168.1.2');
return this.api_;
}
static setDb(v) {
@ -27,19 +30,9 @@ class Registry {
static db() {
if (!this.db_) throw new Error('Accessing database before it has been initialised');
// if (!this.db_) {
// this.db_ = new Database();
// this.db_.setDebugEnabled(this.debugMode());
// this.db_.open();
// }
return this.db_;
}
static api() {
if (!this.api_) throw new Error('Accessing web API before it has been initialised');
return this.api_;
}
}
export { Registry };

View File

@ -104,6 +104,7 @@ class AppComponent extends React.Component {
Log.info('Loading settings...');
return Setting.load();
}).then(() => {
Log.info('Client ID', Setting.value('clientId'));
Log.info('Loading notes...');
Note.previews().then((notes) => {
this.props.dispatch({

View File

@ -0,0 +1,11 @@
import createUuidV4 from 'uuid/v4';
const uuid = {
create: function() {
return createUuidV4().replace(/-/g, '');
}
}
export { uuid };

View File

@ -1,4 +1,5 @@
const queryString = require('query-string');
import { Log } from 'src/log.js';
import { stringify } from 'query-string';
class WebApi {
@ -9,7 +10,7 @@ class WebApi {
makeRequest(method, path, query, data) {
let url = this.baseUrl_;
if (path) url += '/' + path;
if (query) url += '?' + queryString(query);
if (query) url += '?' + stringify(query);
let options = {};
options.method = method.toUpperCase();
if (data) {
@ -27,16 +28,33 @@ class WebApi {
};
}
static toCurl(r, data) {
let o = r.options;
let cmd = [];
cmd.push('curl');
if (o.method == 'PUT') cmd.push('-X PUT');
if (o.method == 'PATCH') cmd.push('-X PATCH');
if (o.method == 'DELETE') cmd.push('-X DELETE');
if (o.method != 'GET' && o.method != 'DELETE') {
cmd.push("--data '" + stringify(data) + "'");
}
cmd.push(r.url);
return cmd.join(' ');
}
exec(method, path, query, data) {
let that = this;
return new Promise(function(resolve, reject) {
let r = that.makeRequest(method, path, query, data);
Log.debug(WebApi.toCurl(r, data));
fetch(r.url, r.options).then(function(response) {
let responseClone = response.clone();
return response.json().then(function(data) {
if (data && data.error) {
reject(data);
let e = new Error(data.error);
reject(e);
} else {
resolve(data);
}
@ -46,11 +64,9 @@ class WebApi {
reject(new Error('Cannot parse JSON: ' + text));
});
});
})
.then(function(data) {
}).then(function(data) {
resolve(data);
})
.catch(function(error) {
}).catch(function(error) {
reject(error);
});
});

View File

@ -24,10 +24,10 @@ class Session extends BaseModel {
static public function login($email, $password, $clientId) {
$user = User::byEmail($email);
if (!$user) throw new NotFoundException("User not found");
if (!$user) throw new AuthException("User not found");
$ok = self::verifyPassword($password, $user->password);
if (!$ok) throw new AuthException();
if (!$ok) throw new AuthException('Invalid password');
$session = new Session();
$session->owner_id = $user->id;