• 【AGC】如何使用认证服务与云数据库处理用户信息


    使用场景

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

    集成准备

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

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

    cke_405.png

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

    cke_2714.png

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

    cke_4181.png

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

    cke_6024.png

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

    cke_8517.png

    6、集成认证服务SDK。

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

    布局设计

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

    1. "1.0" encoding="utf-8"?>
    2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. tools:context=".LoginActivity">
    8. <TextView
    9. android:layout_width="wrap_content"
    10. android:layout_height="wrap_content"
    11. android:text="Welcome to AGC usecase"
    12. android:textSize="24dp"
    13. android:textAlignment="center"
    14. app:layout_constraintBottom_toBottomOf="parent"
    15. app:layout_constraintLeft_toLeftOf="parent"
    16. app:layout_constraintRight_toRightOf="parent"
    17. app:layout_constraintTop_toTopOf="parent"
    18. app:layout_constraintVertical_bias="0.2" />
    19. <LinearLayout
    20. android:layout_width="wrap_content"
    21. android:layout_height="wrap_content"
    22. android:orientation="horizontal"
    23. app:layout_constraintBottom_toBottomOf="parent"
    24. app:layout_constraintHorizontal_bias="0.5"
    25. app:layout_constraintLeft_toLeftOf="parent"
    26. app:layout_constraintRight_toRightOf="parent"
    27. app:layout_constraintTop_toTopOf="parent"
    28. app:layout_constraintVertical_bias="0.35">
    29. <EditText
    30. android:id="@+id/et_countryCode"
    31. android:layout_width="60dp"
    32. android:layout_height="40dp"
    33. android:layout_marginRight="10dp"
    34. android:hint="country code"
    35. android:layout_marginLeft="20dp"
    36. android:inputType="number"
    37. />
    38. <EditText
    39. android:id="@+id/et_phoneNumber"
    40. android:layout_width="200dp"
    41. android:layout_height="40dp"
    42. android:layout_marginRight="20dp"
    43. android:hint="phone number"
    44. android:inputType="number"/>
    45. LinearLayout>
    46. <LinearLayout
    47. android:layout_width="wrap_content"
    48. android:layout_height="wrap_content"
    49. app:layout_constraintBottom_toBottomOf="parent"
    50. app:layout_constraintHorizontal_bias="0.5"
    51. app:layout_constraintLeft_toLeftOf="parent"
    52. app:layout_constraintRight_toRightOf="parent"
    53. app:layout_constraintTop_toTopOf="parent"
    54. app:layout_constraintVertical_bias="0.45">
    55. <EditText
    56. android:id="@+id/et_verifyCode"
    57. android:layout_width="170dp"
    58. android:layout_height="match_parent"
    59. android:layout_marginLeft="20dp"
    60. android:hint="verification code"
    61. android:inputType="number" />
    62. <Button
    63. android:id="@+id/bt_obtain"
    64. android:layout_width="100dp"
    65. android:layout_height="wrap_content"
    66. android:layout_marginRight="10dp"
    67. android:layout_marginLeft="20dp"
    68. android:textSize="15sp"
    69. android:text="Obtaining Verification Code" />
    70. LinearLayout>
    71. <LinearLayout
    72. android:layout_width="200dp"
    73. android:layout_height="45dp"
    74. android:gravity="center_horizontal"
    75. app:layout_constraintBottom_toBottomOf="parent"
    76. app:layout_constraintHorizontal_bias="0.5"
    77. app:layout_constraintLeft_toLeftOf="parent"
    78. app:layout_constraintRight_toRightOf="parent"
    79. app:layout_constraintTop_toTopOf="parent"
    80. app:layout_constraintVertical_bias="0.7">
    81. <Button
    82. android:id="@+id/bt_phoneLogin"
    83. android:layout_width="match_parent"
    84. android:layout_height="match_parent"
    85. android:layout_gravity="center_horizontal"
    86. android:text="Mobile number login"
    87. android:textSize="18sp" />
    88. LinearLayout>
    89. androidx.constraintlayout.widget.ConstraintLayout>

    2、效果展示:

    cke_25010.png

    功能实现

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

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

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

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

    1. VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
    2. .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
    3. .sendInterval(30)
    4. .locale(Locale.SIMPLIFIED_CHINESE)
    5. .build();
    6. String countryCode = et_countryCode.getText().toString().trim();
    7. String phoneNumber = et_phoneNumber.getText().toString().trim();
    8. if (notEmptyString(countryCode) && notEmptyString(phoneNumber)) {
    9. Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countryCode, phoneNumber, settings);
    10. task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
    11. @Override
    12. public void onSuccess(VerifyCodeResult verifyCodeResult) {
    13. Toast.makeText(LoginActivity.this, "验证码已发送。",
    14. Toast.LENGTH_SHORT).show();
    15. }
    16. }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
    17. @Override
    18. public void onFailure(Exception e) {
    19. Toast.makeText(LoginActivity.this, "发送验证码失败。" + e,
    20. Toast.LENGTH_SHORT).show();
    21. Log.e(TAG, "requestVerifyCode fail:" + e);
    22. }
    23. });
    24. } else {
    25. Toast.makeText(LoginActivity.this, "请输入电话号码和国家码。",
    26. Toast.LENGTH_SHORT).show();
    27. }

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

    1. AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(
    2. countryCode,
    3. phoneNumber,
    4. null, // password, can be null
    5. verifyCode);

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

    1. AGConnectAuth.getInstance().signIn(credential)
    2. .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
    3. @Override
    4. public void onSuccess(SignInResult signInResult) {
    5. //获取登录信息
    6. String uid = signInResult.getUser().getUid();
    7. String phoneNumber = signInResult.getUser().getPhone();
    8. redirect(uid,phoneNumber);
    9. }
    10. })
    11. .addOnFailureListener(new OnFailureListener() {
    12. @Override
    13. public void onFailure(Exception e) {
    14. Toast.makeText(LoginActivity.this, "登录失败。" +e.getMessage(),
    15. Toast.LENGTH_SHORT).show();
    16. Log.e(TAG, "Login error, error:" + e.getMessage());
    17. }
    18. });

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

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

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

    1. public void createObjectType() {
    2. try {
    3. mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
    4. Log.i(TAG,"createObjectType: success" );
    5. } catch (AGConnectCloudDBException e) {
    6. Log.e(TAG, "createObjectType: " + e.getMessage());
    7. }
    8. }

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

    1. mConfig = new CloudDBZoneConfig("UsecaseDemo",
    2. CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
    3. CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
    4. mConfig.setPersistenceEnabled(true);
    5. Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
    6. openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
    7. Log.i(TAG, "Open cloudDBZone success");
    8. mCloudDBZone = cloudDBZone;
    9. addSubscription();
    10. }).addOnFailureListener(e -> {
    11. Log.e(TAG, "Open cloudDBZone failed for " + e.getMessage());
    12. });

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

    1. public void upsertUserInfo(UserInfo userInfo) {
    2. if (mCloudDBZone == null) {
    3. Log.w(TAG, "CloudDBZone is null, try re-open it");
    4. return;
    5. }
    6. Task<Integer> upsertTask = mCloudDBZone.executeUpsert(userInfo);
    7. upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
    8. ArrayList<UserInfo> userInfos = new ArrayList<>();
    9. userInfos.add(userInfo);
    10. Log.i(TAG, "Upsert " + cloudDBZoneResult + " records");
    11. }).addOnFailureListener(e -> {
    12. Log.e(TAG, "upsert Error: " + e.getMessage());
    13. });
    14. }

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

    1. public void queryUserInfo(CloudDBZoneQuery query) {
    2. if (mCloudDBZone == null) {
    3. Log.w(TAG, "CloudDBZone is null, try re-open it");
    4. return;
    5. }
    6. Task<CloudDBZoneSnapshot<UserInfo>> queryTask = mCloudDBZone.executeQuery(query,
    7. CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
    8. queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<UserInfo>>() {
    9. @Override
    10. public void onSuccess(CloudDBZoneSnapshot snapshot) {
    11. Log.w(TAG, "Query list from cloud userInfos success");
    12. processQueryResult(snapshot);
    13. }
    14. }).addOnFailureListener(new OnFailureListener() {
    15. @Override
    16. public void onFailure(Exception e) {
    17. Log.e(TAG, "Query list from cloud failed Error: " + e.getMessage());
    18. }
    19. });
    20. }

    功能测试

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

    cke_150309.png

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

    参考文档

    云数据库:文档中心 | 华为开发者联盟

    认证服务:文档中心 | 华为开发者联盟

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

  • 相关阅读:
    Java和vue的包含数组组件contains、includes
    java中2个List集合值和顺序完全一样,如何判断他们相等
    2022年人工智能5大发展趋势
    Google guava之ListMultimap简介说明
    设计模式9、组合模式 Composite
    如何最高效实现手机~电脑端文件传输?
    day5-day6【代码随想录】螺旋矩阵II
    MybatisPlus 1 MybatisPlus 入门案例与简介 1.1 入门案例
    顺序表(静态版本)-----动态版本的基础
    【计算机毕业设计】38.网上轰趴预订系统
  • 原文地址:https://blog.csdn.net/weixin_44708240/article/details/126554698