使用场景

华为 AGC认证服务可以为应用快速构建安全可靠的用户认证系统,可以实现多种方式关联认证登录。而如何处理这些多种登录方式的用户信息,例如在应用中发布一个活动,哪些用户参加了哪一个活动,这些信息都可以记录下来。这样AGC的云数据库服务就派上了用场,无需搭建服务器就可以使用的端云协同的数据库产品。结合认证服务与云数据库服务,就可以简单轻松地完成用户信息录入和修改。下面就将带来一个简单的示例,快速集成认证服务与云数据库实现用户数据处理。

集成准备

在开发功能前,需要开通服务、集成SDK等准备。

1、登录AppGallery Connect网站,点击“我的项目”。在导航选择“构建 > 认证”。如果是首次使用认证服务,请点击“立即开通”开通服务。

2、本次示例以手机号登录为例,所以点击启用手机号码认证方式。

3、登录AppGallery Connect网站,点击“我的项目”。在导航选择“构建 > 云数据库”。如果是首次使用云数据库,请点击“立即开通”开通服务。

4、新增并导出对象类型,本次创建的对象类型示例如图。

5、点击“存储区”,新增存储区“UsecaseDemo”。

6、集成认证服务SDK。

7、集成云数据库SDK并导入对象类型。

布局设计

1、参考如下设置布局,具备输入手机号码、获取验证码、输入验证码登录、登出的功能。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to AGC usecase"
android:textSize="24dp"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.2" /> <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.35">
<EditText
android:id="@+id/et_countryCode"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:hint="country code"
android:layout_marginLeft="20dp"
android:inputType="number"
/>
<EditText
android:id="@+id/et_phoneNumber"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_marginRight="20dp"
android:hint="phone number"
android:inputType="number"/>
</LinearLayout> <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.45"> <EditText
android:id="@+id/et_verifyCode"
android:layout_width="170dp"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:hint="verification code"
android:inputType="number" />
<Button
android:id="@+id/bt_obtain"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginLeft="20dp"
android:textSize="15sp"
android:text="Obtaining Verification Code" />
</LinearLayout> <LinearLayout
android:layout_width="200dp"
android:layout_height="45dp"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.7"> <Button
android:id="@+id/bt_phoneLogin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:text="Mobile number login"
android:textSize="18sp" />
</LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>

2、效果展示:

功能实现

用户打开应用后将会提示登录,使用的是认证服务的手机登录功能,输入手机号,获取验证码登录成功后跳转至主页。

1、在应用的登录界面,初始化AGConnectAuth实例,获取AGC的用户信息,检查是否有已经登录的用户。如果有则可以直接进入用户界面,否则显示登录界面。

AGConnectUser user = AGConnectAuth.getInstance().getCurrentUser();
if (user != null){
Toast.makeText(this,"已检测到用户,等待自动登录",Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
String uid = user.getUid();
String phoneNumber = user.getPhone();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("uid", uid);
intent.putExtra("phoneNumber", phoneNumber);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
},1000*2);
}

2、申请手机注册的验证码,在使用手机注册之前,需要先验证您的手机,确保该手机归您所有。通过VerifyCodeSettings.Builder生成settings ,然后调用AGConnectAuth.requestVerifyCode申请验证码。

VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
.action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
.sendInterval(30)
.locale(Locale.SIMPLIFIED_CHINESE)
.build();
String countryCode = et_countryCode.getText().toString().trim();
String phoneNumber = et_phoneNumber.getText().toString().trim();
if (notEmptyString(countryCode) && notEmptyString(phoneNumber)) {
Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countryCode, phoneNumber, settings);
task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
@Override
public void onSuccess(VerifyCodeResult verifyCodeResult) {
Toast.makeText(LoginActivity.this, "验证码已发送。",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(LoginActivity.this, "发送验证码失败。" + e,
Toast.LENGTH_SHORT).show();
Log.e(TAG, "requestVerifyCode fail:" + e);
}
});
} else {
Toast.makeText(LoginActivity.this, "请输入电话号码和国家码。",
Toast.LENGTH_SHORT).show();
}

3、调用PhoneAuthProvider.credentialWithVerifyCode采用验证码方式创建手机帐号凭证。

AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(
countryCode,
phoneNumber,
null, // password, can be null
verifyCode);

4、获取credential成功后,调用AGConnectAuth.signIn实现登录。

AGConnectAuth.getInstance().signIn(credential)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
//获取登录信息
String uid = signInResult.getUser().getUid();
String phoneNumber = signInResult.getUser().getPhone();
redirect(uid,phoneNumber);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(LoginActivity.this, "登录失败。" +e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Login error, error:" + e.getMessage());
}
});

5、通过initialize()方法初始化AGConnectCloudDB。

public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}

6、使用createObjectType()创建对象类型。

public void createObjectType() {
try {
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
Log.i(TAG,"createObjectType: success" );
} catch (AGConnectCloudDBException e) {
Log.e(TAG, "createObjectType: " + e.getMessage());
}
}

7、创建Cloud DB zone配置对象,并打开该Cloud DB zone。

mConfig = new CloudDBZoneConfig("UsecaseDemo",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
Log.i(TAG, "Open cloudDBZone success");
mCloudDBZone = cloudDBZone;
addSubscription();
}).addOnFailureListener(e -> {
Log.e(TAG, "Open cloudDBZone failed for " + e.getMessage());
});

8、通过executeUpsert()将用户信息插入到云数据库。

public void upsertUserInfo(UserInfo userInfo) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> upsertTask = mCloudDBZone.executeUpsert(userInfo);
upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
ArrayList<UserInfo> userInfos = new ArrayList<>();
userInfos.add(userInfo);
Log.i(TAG, "Upsert " + cloudDBZoneResult + " records");
}).addOnFailureListener(e -> {
Log.e(TAG, "upsert Error: " + e.getMessage());
});
}

9、查询所有用户的信息。

public void queryUserInfo(CloudDBZoneQuery<UserInfo> query) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<CloudDBZoneSnapshot<UserInfo>> queryTask = mCloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<UserInfo>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<UserInfo> snapshot) {
Log.w(TAG, "Query list from cloud userInfos success");
processQueryResult(snapshot);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "Query list from cloud failed Error: " + e.getMessage());
}
});
}

功能测试

将项目打包后测试,使用手机号认证登录,选择某一预置的活动参加,在AGC控制台云数据库中就可以查看登录用户的信息。

这样就可以快速实现认证服务登录用户信息的增删改查。

参考文档

云数据库:https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-clouddb-introduction-0000001054212760

认证服务:https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-auth-introduction-0000001053732605

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

【AGC】如何使用认证服务与云数据库处理用户信息的更多相关文章

  1. python实现用户登陆(sqlite数据库存储用户信息)

    python实现用户登陆(sqlite数据库存储用户信息) 目录 创建数据库 数据库管理 简单登陆 有些地方还未完善. 创建数据库 import sqlite3 #建一个数据库 def create_ ...

  2. servlet+jsp+jdbc实现从数据库查询用户信息到页面

    工程创建这里就不在累述了,直接从显示User信息列表开始. 备注:我用的是servlet3的注解功能实现的,所以不需要配置web.xml 这是我的工程目录: 首先我们创建实体类: public cla ...

  3. oracle查询数据库所有用户信息

    看到网上说的查询用户的语句: SELECT * FROM dba_users;这句好像只能系统管理员才能成功执行,普通用户无法执行 SELECT count(*) FROM all_users; , ...

  4. freeswitch用户整合(使用mysql数据库的用户表)

    转:freeswitch用户整合(使用mysql数据库的用户表) freeswitch是一款强大的voip服务器,可以语音和视频.但是它默认是采用/directory文件夹下的xml来配置用户的,对于 ...

  5. GreenPlum 数据库创建用户、文件空间、表空间、数据库

    前几篇文章介绍了GreenPlum数据库的安装.启动.关闭.状态检查.登录等操作,数据库已经创建好了,接下来介绍如何使用数据库.按照习惯,需要先创建测试用户.表空间.数据库.先创建测试用户dbdrea ...

  6. 华为云函数中使用云数据库的JavaScript SDK基础入门

    背景介绍 使用云数据库Server端的SDK,此处我以华为提供的官方Demo为例,他们的Demo也已经开源放在了GitHub上,大家需要的可以自行下载. https://github.com/AppG ...

  7. 阿里云产品介绍(三):云数据库RDS

    写完云服务器ECS,本来想先写负载均衡的. 因为发现很多客户,都是直接将单台云服务器应用对外提供访问,如果云服务器宕机,应用就会停止服务.云服务器标称有99.95%的可用率,一年下来宕机四个多小时也是 ...

  8. 阿里云数据库RDS环境搭建

    前言 现在云数据库越来越流行,国外的亚马逊AWS微软Azure,国内的BAT和京东都推出了自己的云数据库服务,各自优劣不表,个人推荐国外的用AWS,国内的用阿里云,这是我这几天刚申请的阿里云的过程的一 ...

  9. 云数据库 Bmob

    /**************************************************************************************** * 云数据库 Bmo ...

随机推荐

  1. 覆盖率检查工具:JaCoCo 食用指南

    一:概述 众所周知,软件的代码覆盖率是衡量软件质量的重要指标, 我们今天简单介绍 JaCoCo 的实际使用示例,它是目前在大多数 Java 项目中应用最广泛的覆盖率检测框架 更多资料参考:JaCoCo ...

  2. 2 万字 + 20张图| 细说 Redis 九种数据类型和应用场景

    作者:小林coding 计算机八股文网(操作系统.计算机网络.计算机组成.MySQL.Redis):https://xiaolincoding.com 大家好,我是小林. 我们都知道 Redis 提供 ...

  3. python小题目练习(十)

    题目:根据生日判断星座 需求:实现如下图所示结果 代码展示: """Author:mllContent:根据生日判断星座Date:2020-11-23"&quo ...

  4. sql server2016 数据库日志 清空语句

    /*1.查询数据库日志文件名称*/--TC_MES_DEV为数据库名--这里的 数据库日志名,可以用以下注释的语句进行查询(_log那个)USE [TC_MES_DEV]GOSELECT file_i ...

  5. windows server2012R2 上 .net core IIS 部署--应用程序池 自动停止

    在windows server2016安装部署.NET CORE时,只需要将.net core应用程序池设置无托管,然后对应你项目的版本安装一个dotnet-hosting-2.2.6-win.exe ...

  6. 【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示

    前言: MQTT广泛应用于工业物联网.智能家居.各类智能制造或各类自动化场景等.MQTT是一个基于客户端-服务器的消息发布/订阅传输协议,在很多受限的环境下,比如说机器与机器通信.机器与物联网通信等. ...

  7. Math类和函数定义

    Math这个类是java系统内部当中的一个类,他用来提供一些基本的数学操作,他也有些工具可以给我们用比如 :abs--算绝对值   pow--算幂次   random--随机数   round--四舍 ...

  8. Kafka启动遇到ERROR Exiting Kafka due to fatal exception (kafka.Kafka$) 解决办法 从kafka的根目录启动 bin/kafka-server-start.sh config/server.properties

    Mysql配置读写数据库 ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) fo ...

  9. 零基础学Java(6)控制流程

    控制流程 与任何程序设计语言一样,Java使用条件语句和循环结构确定控制流程. 块作用域 我们首先要了解块(block)的概念. 块是指由若干条Java语句组成的语句,并用一对大括号括起来.块确定了变 ...

  10. day01 File类_Lambda

    File类 File类的每一个实例可以表示硬盘(文件系统)中的一个文件或目录(实际上表示的是一个抽象路径) 使用File可以做到: 1:访问其表示的文件或目录的属性信息,例如:名字,大小,修改时间等等 ...