Selaa lähdekoodia

登录/自动登录

hh 1 vuosi sitten
vanhempi
commit
837c4c55b8

+ 2 - 0
entry/src/main/ets/common/constants/CommonConstants.ets

@@ -57,6 +57,8 @@ import RobotInfo from '../../model/RobotInfo'
 export default class CommonConstants {
 
     static readonly RDB_NAME : string = 'Presentation.db'
+    static readonly PRE_NAME : string = 'MyPreferences'
+    static AUTH_TOKEN : string = ''
 
     static readonly STORAGE_TYPE: string[] =  ['电子元器件', '电路板', '结构件', '辅助材料']
     static readonly PARK_TYPE: string[] =  ['出入库位置', '充电位置', '工作台', '其他']

+ 3 - 1
entry/src/main/ets/common/util/request/Request.ets

@@ -1,4 +1,6 @@
 import axios, { AxiosError, AxiosResponse, AxiosRequestHeaders,AxiosRequestConfig, CreateAxiosDefaults,InternalAxiosRequestConfig } from '@ohos/axios';
+import CommonConstants from '../../constants/CommonConstants';
+import PreferencesUtil from '../PreferencesUtil';
 import { printError, printRequest, printResponse, handleRes } from './Helps';
 
 const baseUrl = "http://192.168.101.4:8079/"
@@ -19,7 +21,7 @@ const JGRequest = axios.create(
 JGRequest.interceptors.request.use((config: InternalAxiosRequestConfig) => {
 
   // 以后登录之后可以在这里传
-  // config.headers.Authorization = "测试接口请求token"
+  config.headers.Authorization = CommonConstants.AUTH_TOKEN
 
   printRequest(config)
 

+ 6 - 1
entry/src/main/ets/common/util/request/RequestInstance.ets

@@ -1,3 +1,4 @@
+import UserInfo from '../../../model/UserInfo'
 import JGRequest from './Request'
 
 const getToken = async (loginName: string, password: string, orgId: number, stationId: number): Promise<string> => {
@@ -9,4 +10,8 @@ const getToken = async (loginName: string, password: string, orgId: number, stat
   })
 }
 
-export{getToken}
+const getUserInfo = async (): Promise<UserInfo> => {
+  return await JGRequest.get("/api/auth", {})
+}
+
+export{getToken, getUserInfo}

+ 2 - 1
entry/src/main/ets/common/util/request/StorageRequest.ets

@@ -1,4 +1,5 @@
 import axios, { AxiosError, AxiosResponse, AxiosRequestHeaders,AxiosRequestConfig, CreateAxiosDefaults,InternalAxiosRequestConfig } from '@ohos/axios';
+import CommonConstants from '../../constants/CommonConstants';
 import { printError, printRequest, printResponse, handleRes } from './Helps';
 
 const baseUrl = "http://192.168.101.4:8088/"
@@ -19,7 +20,7 @@ const StorageRequest = axios.create(
 StorageRequest.interceptors.request.use((config: InternalAxiosRequestConfig) => {
 
   // 以后登录之后可以在这里传
-  // config.headers.Authorization = "测试接口请求token"
+  config.headers.Authorization = CommonConstants.AUTH_TOKEN
 
   printRequest(config)
 

+ 3 - 18
entry/src/main/ets/entryability/EntryAbility.ets

@@ -6,30 +6,17 @@ import window from '@ohos.window';
 import RobotSelfCheckModel from '../model/database/RobotSelfCheckModel';
 import StorageModel from '../model/database/StorageModel';
 import StorageSpaceModel from '../model/database/StorageSpaceModel';
-import PreferencesUtil from '../common/util/PreferencesUtil';
-import UserSetModel from '../model/database/UserSetModel';
-import UserSet from '../model/UserSet';
+import UserModel from '../model/database/UserModel';
 
 export default class EntryAbility extends UIAbility {
+
   async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
     hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
     // 初始化表
     RobotSelfCheckModel.initTaskDB(this.context)
     StorageSpaceModel.initTaskDB(this.context)
     StorageModel.initTaskDB(this.context)
-    UserSetModel.initTaskDB(this.context)
-    // 加载Preferences
-    await PreferencesUtil.loadPreference(this.context, 'MyPreferences')
-
-    await UserSetModel.getLast().then(userSet=>{
-      if (userSet && userSet.maintainLoginStatus === 1) {
-
-      }
-    })
-
-
-
-
+    UserModel.initTaskDB(this.context)
   }
 
   onDestroy(): void {
@@ -50,8 +37,6 @@ export default class EntryAbility extends UIAbility {
 
       windowClass = data;
       console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
-
-
       // 2.实现沉浸式效果:设置导航栏、状态栏不显示。
       let names = [];
       windowClass.setWindowSystemBarEnable(names, (err) => {

+ 19 - 0
entry/src/main/ets/model/UserInfo.ets

@@ -0,0 +1,19 @@
+// 用户信息
+export default class UserInfo {
+  // id
+  id?: number;
+  // 仓储id
+  userId?: number;
+  // 用户名
+  userName?: string;
+  // 登录密码
+  password?: string;
+  // 组织id
+  orgId?: number;
+  // 工位id
+  stationId?: number;
+  // 保持登录状态(1:是 2:否)
+  maintainLoginStatus?: number;
+  // 更新时间戳
+  updateTime?: number;
+}

+ 0 - 11
entry/src/main/ets/model/UserSet.ets

@@ -1,11 +0,0 @@
-// 用户设置
-export default class UserSet {
-  // id
-  id?: number;
-  // 仓储id
-  userId?: number;
-  // 保持登录状态(1:是 2:否)
-  maintainLoginStatus?: number;
-  // 更新时间戳
-  updateTime?: number;
-}

+ 166 - 0
entry/src/main/ets/model/database/UserModel.ets

@@ -0,0 +1,166 @@
+import relationalStore from '@ohos.data.relationalStore';
+import CommonConstants from '../../common/constants/CommonConstants';
+import UserInfo from '../UserInfo';
+
+class UserModel {
+
+  private rdbStore: relationalStore.RdbStore
+  private tableName: string = 'USER'
+
+  /**
+   * 初始化表
+   */
+  initTaskDB(context){
+    // 1.rdb配置
+    const config = {
+      name: CommonConstants.RDB_NAME,
+      securityLevel: relationalStore.SecurityLevel.S1
+    }
+    // 2.初始化SQL语句
+    const sql = `CREATE TABLE IF NOT EXISTS USER (
+                  ID INTEGER PRIMARY KEY AUTOINCREMENT,
+                  USER_ID INTEGER NOT NULL,
+                  USER_NAME TEXT NOT NULL,
+                  PASSWORD TEXT NOT NULL,
+                  ORG_ID INTEGER NOT NULL,
+                  STATION_ID INTEGER NOT NULL,
+                  MAINTAIN_LOGIN_STATUS INTEGER NOT NULL,
+                  UPDATE_TIME INTEGER NOT NULL
+                 )`
+    // 3.获取rdb
+    relationalStore.getRdbStore(context, config, (err, rdbStore) => {
+      if(err){
+        console.log('testTag', '获取rdbStore失败!')
+        return
+      }
+      // 执行Sql
+      rdbStore.executeSql(sql).then(()=>{
+        console.log('testTag', '创建用户设置表成功!')
+      }).catch(err=>{
+        console.log('testTag', '创建失败')
+      })
+      // 保存rdbStore
+      this.rdbStore = rdbStore
+    })
+  }
+
+  /**
+   * 查询用户设置列表
+   */
+  // async getUserList(){
+  //   // 1.构建查询条件
+  //   let predicates = new relationalStore.RdbPredicates(this.tableName)
+  //   // 2.查询
+  //   let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'MAINTAIN_LOGIN_STATUS'])
+  //   // 3.解析查询结果
+  //   // 3.1.定义一个数组,组装最终的查询结果
+  //   let Users: User[] = []
+  //   // 3.2.遍历封装
+  //   while(!result.isAtLastRow){
+  //     // 3.3.指针移动到下一行
+  //     result.goToNextRow()
+  //     // 3.4.获取数据
+  //     let id = result.getLong(result.getColumnIndex('ID'))
+  //     let userId = result.getLong(result.getColumnIndex('USER_ID'))
+  //     let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
+  //     let updateTime = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
+  //     // 3.5.封装到数组
+  //     Users.push({id: id, userId: userId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime})
+  //   }
+  //   return Users
+  // }
+
+  // 查询最后一次用户登录的数据
+  async getLast(): Promise<UserInfo> {
+    // 1.构建查询条件
+    let predicates = new relationalStore.RdbPredicates(this.tableName)
+    predicates.orderByDesc('UPDATE_TIME')
+    predicates.limitAs(1)
+    // 2.查询
+    let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'USER_NAME', 'PASSWORD', 'ORG_ID', 'STATION_ID', 'MAINTAIN_LOGIN_STATUS', 'UPDATE_TIME'])
+    // 3.2.遍历封装 只取第一条
+    while(!result.isAtLastRow){
+      // 3.3.指针移动到下一行
+      result.goToNextRow()
+      // 3.4.获取数据
+      let id = result.getLong(result.getColumnIndex('ID'))
+      let userId = result.getLong(result.getColumnIndex('USER_ID'))
+      let userName = result.getString(result.getColumnIndex('USER_NAME'))
+      let password = result.getString(result.getColumnIndex('PASSWORD'))
+      let orgId = result.getLong(result.getColumnIndex('ORG_ID'))
+      let stationId = result.getLong(result.getColumnIndex('STATION_ID'))
+      let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
+      let updateTime = result.getLong(result.getColumnIndex('UPDATE_TIME'))
+      return {id: id, userId: userId, userName: userName, password: password, orgId: orgId, stationId: stationId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime}
+    }
+  }
+
+  // 查询最后一次用户登录的数据
+  async getByUserId(userId: number): Promise<UserInfo> {
+    if (!userId) {
+      return
+    }
+    // 1.构建查询条件
+    let predicates = new relationalStore.RdbPredicates(this.tableName)
+    predicates.equalTo('USER_ID', userId)
+    predicates.orderByDesc('UPDATE_TIME')
+    predicates.limitAs(1)
+    // 2.查询
+    let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'USER_NAME', 'PASSWORD', 'ORG_ID', 'STATION_ID', 'MAINTAIN_LOGIN_STATUS', 'UPDATE_TIME'])
+    // 3.2.遍历封装 只取第一条
+    while(!result.isAtLastRow){
+      // 3.3.指针移动到下一行
+      result.goToNextRow()
+      // 3.4.获取数据
+      let id = result.getLong(result.getColumnIndex('ID'))
+      let userId = result.getLong(result.getColumnIndex('USER_ID'))
+      let userName = result.getString(result.getColumnIndex('USER_NAME'))
+      let password = result.getString(result.getColumnIndex('PASSWORD'))
+      let orgId = result.getLong(result.getColumnIndex('ORG_ID'))
+      let stationId = result.getLong(result.getColumnIndex('STATION_ID'))
+      let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
+      let updateTime = result.getLong(result.getColumnIndex('UPDATE_TIME'))
+      return {id: id, userId: userId, userName: userName, password: password, orgId: orgId, stationId: stationId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime}
+    }
+  }
+
+  /**
+   * 添加用户设置
+   * @param user 用户信息
+   * @returns 用户信息id
+   */
+  addUser(user: UserInfo): Promise<number>{
+    return this.rdbStore.insert(this.tableName, {USER_ID: user.userId, USER_NAME: user.userName, PASSWORD: user.password, ORG_ID: user.orgId, STATION_ID: user.stationId, MAINTAIN_LOGIN_STATUS: user.maintainLoginStatus, UPDATE_TIME: user.updateTime})
+  }
+
+  /**
+   * 根据id更新用户设置状态
+   * @param id 任务id
+   * @param finished 任务是否完成
+   */
+  updateUser(user: UserInfo) {
+    // 1.要更新的数据
+    let data = {USER_ID: user.userId, USER_NAME: user.userName, PASSWORD: user.password, ORG_ID: user.orgId, STATION_ID: user.stationId, MAINTAIN_LOGIN_STATUS: user.maintainLoginStatus, UPDATE_TIME: user.updateTime}
+    // 2.更新的条件
+    let predicates = new relationalStore.RdbPredicates(this.tableName)
+    predicates.equalTo('ID', user.id)
+    // 3.更新操作
+    return this.rdbStore.update(data, predicates)
+  }
+
+  /**
+   * 根据id删除任务
+   * @param id 任务id
+   */
+  deleteUserById(id: number){
+    // 1.删除的条件
+    let predicates = new relationalStore.RdbPredicates(this.tableName)
+    predicates.equalTo('ID', id)
+    // 2.删除操作
+    return this.rdbStore.delete(predicates)
+  }
+}
+
+let userModel = new UserModel();
+
+export default userModel as UserModel;

+ 0 - 143
entry/src/main/ets/model/database/UserSetModel.ets

@@ -1,143 +0,0 @@
-import relationalStore from '@ohos.data.relationalStore';
-import CommonConstants from '../../common/constants/CommonConstants';
-import UserSet from '../UserSet';
-
-class UserSetModel {
-
-  private rdbStore: relationalStore.RdbStore
-  private tableName: string = 'USER_SET'
-
-  /**
-   * 初始化表
-   */
-  initTaskDB(context){
-    // 1.rdb配置
-    const config = {
-      name: CommonConstants.RDB_NAME,
-      securityLevel: relationalStore.SecurityLevel.S1
-    }
-    // 2.初始化SQL语句
-    const sql = `CREATE TABLE IF NOT EXISTS USER_SET (
-                  ID INTEGER PRIMARY KEY AUTOINCREMENT,
-                  USER_ID INTEGER NOT NULL,
-                  MAINTAIN_LOGIN_STATUS INTEGER NOT NULL,
-                  UPDATE_TIME INTEGER NOT NULL
-                 )`
-    // 3.获取rdb
-    relationalStore.getRdbStore(context, config, (err, rdbStore) => {
-      if(err){
-        console.log('testTag', '获取rdbStore失败!')
-        return
-      }
-      // 执行Sql
-      rdbStore.executeSql(sql).then(()=>{
-        console.log('testTag', '创建用户设置表成功!')
-      }).catch(err=>{
-        console.log('testTag', '创建失败')
-      })
-      // 保存rdbStore
-      this.rdbStore = rdbStore
-    })
-  }
-
-  /**
-   * 查询用户设置列表
-   */
-  // async getUserSetList(){
-  //   // 1.构建查询条件
-  //   let predicates = new relationalStore.RdbPredicates(this.tableName)
-  //   // 2.查询
-  //   let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'MAINTAIN_LOGIN_STATUS'])
-  //   // 3.解析查询结果
-  //   // 3.1.定义一个数组,组装最终的查询结果
-  //   let userSets: UserSet[] = []
-  //   // 3.2.遍历封装
-  //   while(!result.isAtLastRow){
-  //     // 3.3.指针移动到下一行
-  //     result.goToNextRow()
-  //     // 3.4.获取数据
-  //     let id = result.getLong(result.getColumnIndex('ID'))
-  //     let userId = result.getLong(result.getColumnIndex('USER_ID'))
-  //     let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-  //     let updateTime = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-  //     // 3.5.封装到数组
-  //     userSets.push({id: id, userId: userId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime})
-  //   }
-  //   return userSets
-  // }
-
-  // 查询最后一次用户登录的数据
-  async getLast(): Promise<UserSet> {
-    // 1.构建查询条件
-    let predicates = new relationalStore.RdbPredicates(this.tableName)
-    predicates.orderByDesc('UPDATE_TIME')
-    predicates.limitAs(1)
-    // 2.查询
-    let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'MAINTAIN_LOGIN_STATUS', 'UPDATE_TIME'])
-    // 3.4.获取数据
-    let id = result.getLong(result.getColumnIndex('ID'))
-    let userId = result.getLong(result.getColumnIndex('USER_ID'))
-    let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-    let updateTime = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-    return {id: id, userId: userId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime}
-  }
-
-  // 查询最后一次用户登录的数据
-  async getByUserId(userId: number): Promise<UserSet> {
-    // 1.构建查询条件
-    let predicates = new relationalStore.RdbPredicates(this.tableName)
-    predicates.equalTo('USER_ID', userId)
-    predicates.orderByDesc('UPDATE_TIME')
-    predicates.limitAs(1)
-    // 2.查询
-    let result = await this.rdbStore.query(predicates, ['ID', 'USER_ID', 'MAINTAIN_LOGIN_STATUS', 'UPDATE_TIME'])
-    // 3.4.获取数据
-    let id = result.getLong(result.getColumnIndex('ID'))
-    let maintainLoginStatus = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-    let updateTime = result.getLong(result.getColumnIndex('MAINTAIN_LOGIN_STATUS'))
-    return {id: id, userId: userId, maintainLoginStatus: maintainLoginStatus, updateTime: updateTime}
-  }
-
-  /**
-   * 添加用户设置
-   * @param UserSetName 用户设置名称
-   * @param xSize x尺寸
-   * @param ySize y尺寸
-   * @param defaultLayer 默认尺寸
-   * @returns 用户设置id
-   */
-  addUserSet(userId: number, maintainLoginStatus: number, updateTime: number): Promise<number>{
-      return this.rdbStore.insert(this.tableName, {USER_ID: userId, MAINTAIN_LOGIN_STATUS: maintainLoginStatus, UPDATE_TIME: updateTime})
-  }
-
-  /**
-   * 根据id更新用户设置状态
-   * @param id 任务id
-   * @param finished 任务是否完成
-   */
-  updateUserSet(id: number, userId: number, maintainLoginStatus: number, updateTime: number) {
-    // 1.要更新的数据
-    let data = {USER_ID: userId, MAINTAIN_LOGIN_STATUS: maintainLoginStatus, UPDATE_TIME: updateTime}
-    // 2.更新的条件
-    let predicates = new relationalStore.RdbPredicates(this.tableName)
-    predicates.equalTo('ID', id)
-    // 3.更新操作
-    return this.rdbStore.update(data, predicates)
-  }
-
-  /**
-   * 根据id删除任务
-   * @param id 任务id
-   */
-  deleteUserSetById(id: number){
-    // 1.删除的条件
-    let predicates = new relationalStore.RdbPredicates(this.tableName)
-    predicates.equalTo('ID', id)
-    // 2.删除操作
-    return this.rdbStore.delete(predicates)
-  }
-}
-
-let userSetModel = new UserSetModel();
-
-export default userSetModel as UserSetModel;

+ 36 - 6
entry/src/main/ets/pages/LoginPage.ets

@@ -1,6 +1,9 @@
 import router from '@ohos.router'
+import CommonConstants from '../common/constants/CommonConstants'
 import JGRequest from '../common/util/request/Request'
-import {getToken} from '../common/util/request/RequestInstance'
+import {getToken, getUserInfo} from '../common/util/request/RequestInstance'
+import UserModel from '../model/database/UserModel';
+import UserInfo from '../model/UserInfo'
 
 @Entry
 @Component
@@ -34,6 +37,20 @@ struct LoginPage {
     customStyle: true,
   })
 
+  async aboutToAppear() {
+    let userInfo = await UserModel.getLast() as UserInfo
+    if (userInfo && userInfo.maintainLoginStatus === 1) {
+      await getToken(userInfo.userName, userInfo.password, userInfo.orgId, userInfo.stationId).then(token=>{
+        if (token && token.length > 0) {
+          CommonConstants.AUTH_TOKEN = token
+          router.pushUrl({
+            url:'pages/Index'
+          })
+        }
+      })
+    }
+  }
+
   build() {
     Column() {
       Column() {
@@ -168,15 +185,28 @@ struct LoginPage {
             .borderRadius($r('app.float.robot_set_radius'))
             .opacity(this.loginName && this.loginName.length > 0 && this.password && this.password.length > 0 ? 1 : $r('app.float.card_font_default_opacity'))
         }
-        .onClick(()=>{
+        .onClick(async ()=>{
           if (this.loginName && this.loginName.length > 0 && this.password && this.password.length > 0) {
-            getToken(this.loginName, this.password, this.dept ? this.dept.id : 0, this.workstation ? this.workstation.id : 0).then(token =>{
+            await getToken(this.loginName, this.password, this.dept ? this.dept.id : 0, this.workstation ? this.workstation.id : 0).then(token =>{
               if (token && token.length > 0) {
-                router.pushUrl({
-                  url:'pages/Index'
-                })
+                CommonConstants.AUTH_TOKEN = token
               }
             })
+            if (CommonConstants.AUTH_TOKEN.length <= 0) {
+              return
+            }
+            let userInfo = await getUserInfo() as UserInfo
+            let user = await UserModel.getByUserId(userInfo.id) as UserInfo
+            if (!user || !user.id) {
+              // 将后端数据库id作为userId, 默认是保持登录
+              user = {userId: userInfo.id, userName: this.loginName, password: this.password, orgId: this.dept ? this.dept.id : 0,
+                stationId: this.workstation ? this.workstation.id : 0, maintainLoginStatus: 1, updateTime: new Date().getTime()}
+              let result = await UserModel.addUser(user)
+              console.log('testTag','---addResult-----' + JSON.stringify(result));
+            }
+            router.pushUrl({
+              url:'pages/Index'
+            })
           }
         })
         .width('90.4%')