Dataset Viewer
text
stringlengths 8
1.05M
| repo_path
stringlengths 4
291
| keyword
sequencelengths 1
25
| text_hash
stringlengths 64
64
|
---|---|---|---|
import os
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from main_window import Ui_MainWindow
from multiprocessing import Process
from builtins import str
if (os.name == 'nt'):
import vtk
vtk.vtkObject.GlobalWarningDisplayOff()
import compute_areas
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parameters, *args):
super(MainWindow, self).__init__(*args)
Ui_MainWindow.setupUi(self, self)
self.last_dir = os.path.expanduser("~")
self.connect_signals()
if not parameters:
self.precisionSpinBox.hide()
self.precisionLabel.hide()
self.exportResolutionLabel.hide()
self.exportReductionDoubleSpinBox.hide()
self.includeSegmentsCheckBox.hide()
self.includeSegmentsLabel.hide()
self.kernelSizeSpinBox.hide()
self.kernelSizeLabel.hide()
self.cleanVrmlCheckBox.hide()
self.cleanVrmlLabel.hide()
def connect_signals(self):
self.one_vrml_button.clicked.connect(lambda: self.open_dialog(self.one_vrml_input, "*.vrml *.imx"))
self.one_vrml_csv_button.clicked.connect(lambda: self.save_dialog(self.one_vrml_csv_input, "*.csv"))
self.many_vrml_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_input))
self.many_vrml_csv_button.clicked.connect(lambda: self.open_dir_dialog(self.many_vrml_csv_input))
self.one_vrml_run_button.clicked.connect(lambda: self.run("one_vrml"))
self.many_vrml_run_button.clicked.connect(lambda: self.run("many_vrml"))
def run(self, kind):
args = []
if kind == "one_vrml":
if not os.path.isfile(self.one_vrml_input.text()):
self.one_vrml_input.setFocus()
return
if self.one_vrml_csv_input.text() == "":
self.one_vrml_csv_input.setFocus()
return
args = ["-a", "{}".format(self.one_vrml_csv_input.text()),
"-v", "{}".format(self.one_vrml_input.text()),
"-s", "{}".format(self.outputFormatComboBox.currentText()),
"-p", "{}".format(self.precisionSpinBox.value()),
"-r", "{}".format(self.exportReductionDoubleSpinBox.value()),
"-f", "{}".format(self.includeSegmentsCheckBox.isChecked()),
"-k", "{}".format(self.kernelSizeSpinBox.value()),
"-c", "{}".format(self.cleanVrmlCheckBox.isChecked())]
if kind == "many_vrml":
if not os.path.isdir(self.many_vrml_input.text()):
self.many_vrml_input.setFocus()
return
if not os.path.isdir(self.many_vrml_csv_input.text()):
self.many_vrml_csv_input.setFocus()
return
args = ["-o", "{}".format(self.many_vrml_csv_input.text()),
"-w", "{}".format(self.many_vrml_input.text()),
"-s", "{}".format(self.outputFormatComboBox.currentText()),
"-p", "{}".format(self.precisionSpinBox.value()),
"-r", "{}".format(self.exportReductionDoubleSpinBox.value()),
"-f", "{}".format(self.includeSegmentsCheckBox.isChecked()),
"-k", "{}".format(self.kernelSizeSpinBox.value()),
"-c", "{}".format(self.cleanVrmlCheckBox.isChecked())]
print("python compute_areas.py " + " ".join(args))
p = Process(target=compute_areas.main, args=[args])
p.start()
self.statusBar.clearMessage()
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
self.tabWidget.setDisabled(True)
self.check_running(p)
def check_running(self, p):
if p.is_alive():
QtCore.QTimer.singleShot(250, lambda: self.check_running(p))
else:
p.join()
if p.exitcode != 0:
self.statusBar.showMessage("ERROR: There was an error computing Areas, try with other vrml/imx")
self.tabWidget.setDisabled(False)
QtWidgets.QApplication.restoreOverrideCursor()
def _handle_file_path(self, file_path):
if type(file_path) is tuple:
file = file_path[0]
else:
file = file_path
self.last_dir = os.path.dirname(file)
return file
def open_dialog(self, target, filter):
file = QtWidgets.QFileDialog.getOpenFileName(self, "Open File",
self.last_dir, filter) # QtCore.QString
file = self._handle_file_path(file)
target.setText(file)
def save_dialog(self, target, filter):
file = QtWidgets.QFileDialog.getSaveFileName(self, "Save File",
self.last_dir, filter) # QtCore.QString
file = self._handle_file_path(file)
target.setText(file)
def open_dir_dialog(self, target):
file = QtWidgets.QFileDialog.getExistingDirectory(self, "Open Folder", self.last_dir) # QtCore.QString
file = self._handle_file_path(file)
target.setText(file)
def main(argv):
app = QtWidgets.QApplication(sys.argv)
mw = MainWindow("-p" in argv)
# mw.one_imx_input.setText("/home/jmorales/sets/imxs/humanas-cingular/Api/api if6 1 8enero LONGS.imx")
# mw.one_csv_input.setText("/tmp/paco.csv")
mw.show()
app.exec_()
if __name__ == '__main__':
main(sys.argv) | src/gui.py | [
"VTK"
] | baa1650e26be8331008b85d9d3222af9c07e60e37772b916d19c1b046a060e9e |
# Sunrider: Mask of Arcadius Enhancement Mod Goals
## Update Dialogue
* Assign character colors, (including characters not present in Liberation Day)
* Update window screen and styles
* Update window text alignment (undetermined)
### Update Quick Menu
* Disappear during the right times
* Stay visible during choices and battle
## Update Choices
* Port dialog screen to menu screen
## Load/Save Menu
* Best of both worlds: Liberation Day layout, with arrow keys for each 10 saves.
## Preferences Menu
* Update bar styles
### Update Battle UI
* Upgrade Movement Energy Cost
* Optional Liberation Day battle Animations (Requires learning battle system)
* Switch combat mechanics to that of Liberation Day (Requires learning battle system)
* Optional Liberation Day Japanese Voices
## Update Galaxy Map
* Highlight locations with missions in Red like in Liberation Day
## Define a skip screen so that we're not using the lame skip text at the top left
* Title says it all
## Bonus Menu
* Viewable CG, backgrounds, etc
* Integrate with deleted scenes menu and (mod select menu?) | goals.md | [
"Galaxy"
] | 0c719a0034712878782c41a8d270075f0c961b2c4dfd5440d28b8d16da588298 |
## Hello World Web Server Example
Stands up a simple lightweight HTTP server on port 8080
Created using `nimble init`
after running visit http://localhost:8080/
## Compiling
To to compile the app run
```shell script
nimble compile
```
## Running
To run the app run
```shell script
nimble run
```
| recipes/hello_world_ws/README.md | [
"VisIt"
] | 9bd40080028a991d21d9f3ced3c4c6bab38a90b78c025e235633c94556adebf0 |
# MyGarden
## Objective:
MyGarden is an application that allows anyone to easily plot an edible garden. Users can focus on the more relaxed motions of building and watching their efforts come to fruition.
### [<ins>MyGarden deployed via Heroku</ins>](https://getmygarden.herokuapp.com/)
## Installation:
## Prerequisites
### Docker
This project relies on Docker to run the PostgreSQL server. You must install
Docker first before continuing.
Use one of these methods:
- Use [Homebrew](https://brew.sh) on macOS:
```sh
brew install --cask docker
```
- [Follow the instructions on the Docker website](https://docs.docker.com/get-docker/)
Once you've installed Docker Desktop, you'll need to launch the app. On macOS,
it's located in `/Applications/Docker`.
### Node
You'll need to install Node v14 or above. [`nvm`](https://github.com/nvm-sh/nvm) is highly recommended.
### Set Up the Development Environment
#### Install NPM Packages
```sh
npm install
```
### Set Up `postgres` User Password and Database Name
Set up information in order to start a new
PostgreSQL server instance, as well as to connect to it later from the Express
server.
1. Copy the example environment file
```sh
cp .env.example .env
```
2. You can choose to edit `.env` or just use as-is.
[See the PostgreSQL Docker image documentation for more
information](https://hub.docker.com/_/postgres).
### Initialize the Database
Let's set up the database server, create the application database, and seed it
with some data. You only need to do this the first time you set up your
development environment.
```sh
npm run db:init
```
ℹ️ If you ever need to start over with the database, you can run this command
again which will delete your existing data and start from scratch.
## Start your Development Environment
```sh
npm start
```
Visit <http://localhost:3000>.
## Shut Down the Development Environment
1. `Ctrl-C` to stop the Express and React development servers.
2. To stop and destroy the PostgreSQL Docker container run. (Don't worry, your data is safe.)
```sh
`npm run db:stop`
```
## Need to Start a `psql` Session?
```sh
npm run psql
```
## Technologies:
1. PostgreSQL, Object-Relational Database
2. Express, backend
3. React, frontend
4. NodeJS, serving Express and React
[//]: # "5. Heroku and GitHub, deployment"
## Application Programming Interfaces:
1. [Auth0 (Securing Single Page React App)](https://auth0.com/docs/libraries/auth0-single-page-app-sdk)
2. [Auth0 (Securing Backend - Authorization)](https://auth0.com/docs/quickstart/backend/nodejs/01-authorization)
3. [Plant Hardiness Zones (Walkdoj)](https://github.com/waldoj/frostline)
## Data Collected From
1. [Vegetation (Trefle)](https://docs.trefle.io/docs/examples/snippets/)
2. [Plants For A Future Database](https://pfaf.org/user/Default.aspx)
## Minimal Viable Product:
### [<ins>Google Doc for MyGarden Project development</ins>](https://docs.google.com/document/d/1HtaY2To8yLveDVoQvEU87eZn97pXQrGPm29APZE1Gio/edit?usp=sharing)
### MVP:
- Easy secure login with Google account or Sign Up.
- Based on user’s zipcode input, display user’s zone.
- Display suggested plants based on user’s zone
- User can save plant selections
### Future Features:
- If user opts for Indoor growing, display plants that don’t need full sun
- User can group plant selections
- User can name plant groupings (containers)
- Plant companions will be displayed
- Plant Groupings will display care instructions per group
- Soil type, watering, light, fertilizer needs
- Spacing, if necessary
- Links, with disclaimers, to helpful articles
- Notify user of upcoming significant changes in weather
- Harsh weather conditions expected //edge cases
- Watering reminders
- Coverings for Heat waves/Frost
- Maintenance Tracking
- Timer/Scheduling
- Watering
- Light
- Fertilizer
- Transplanting Needs
- Crop rotation
- Repotting
## Technical Risks:
- Exploring external API calls.
- Auth0 is said to be difficult to set up.
- Cross-referencing APIs for data extraction.
- Figure out appropriate conditionals to display suggestions for plants.
- Design clean display content with CSS
## Database Schema:

## User Flowchart:

## Wireframes:





| README.md | [
"VisIt"
] | 8484174ccc29570ed9acb82db38e4e4639a9c0c063ac64ce409ac9d503fad03f |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import tensorflow as tf
import inputs
FLAGS = tf.app.flags.FLAGS
# Basic model parameters.
tf.app.flags.DEFINE_integer("num_epochs", 100,
"Number of training epochs (default: 100)")
tf.app.flags.DEFINE_integer("minibatch_size", 128,
"mini Batch Size (default: 64)")
# global constants
# ==================================
# this three dataset related variable are initialized in train.main
# NUM_CLASSES = 0
# NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 0
# NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 0
# output num for conv layer
FEATURE_NUM = 256
# Constants describing the training process.
MOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.
NUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.
LEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.
INITIAL_LEARNING_RATE = 0.1 # Initial learning rate.
# If a model is trained with multiple GPUs, prefix all Op names with tower_name
# to differentiate the operations. Note that this prefix is removed from the
# names of the summaries when visualizing a model.
TOWER_NAME = 'tower'
def initial_dataset_info(dataset):
if dataset == "rotten":
NUM_CLASSES = 2
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 8530
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 2132
elif dataset == "ag":
NUM_CLASSES = 4
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 0
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 0
elif dataset == "newsgroups":
NUM_CLASSES = 4
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 0
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 0
elif dataset == "imdb":
NUM_CLASSES = 2
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 0
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 0
else:
print("wrong dataset:",dataset)
return False
return True
def _activation_summary(x):
"""Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measure the sparsity of activations.
Args:
x: Tensor
Returns:
nothing
"""
# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training
# session. This helps the clarity of presentation on tensorboard.
tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)
tf.histogram_summary(tensor_name + '/activations', x)
tf.scalar_summary(tensor_name + '/sparsity', tf.nn.zero_fraction(x))
def _variable_on_cpu(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of the variable
shape: list of ints
initializer: initializer for Variable
Returns:
Variable Tensor
"""
with tf.device('/cpu:0'):
var = tf.get_variable(name, shape, initializer=initializer)
return var
def _variable_with_weight_decay(name, shape, stddev, wd):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: name of the variable
shape: list of ints
stddev: standard deviation of a truncated Gaussian
wd: add L2Loss weight decay multiplied by this float. If None, weight
decay is not added for this Variable.
Returns:
Variable Tensor
"""
var = _variable_on_cpu(name,
shape,
tf.truncated_normal_initializer(stddev=stddev))
if wd is not None:
weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
def inputs_train():
"""Construct input examples for training process.
Returns:
sequences: 4D tensor of [batch_size, 1, input_length, alphabet_length] size.
labels: Labels. 1D tensor of [batch_size] size.
"""
return inputs.inputs_character("train",
FLAGS.minibatch_size,
FLAGS.num_epochs,
min_shuffle=1000)
def inputs_eval():
"""Construct input examples for evaluations.
similar to inputs_train
"""
# don't shuffle
return inputs.inputs_character("test",
FLAGS.minibatch_size,
None,
min_shuffle=1)
def inference(sequences):
"""Build the CNN model.
Args:
sequences: Sequences returned from inputs_train() or inputs_eval.
Returns:
Logits.
"""
# We instantiate all variables using tf.get_variable() instead of
# tf.Variable() in order to share variables for both training and
# evaluation.
# conv1
with tf.variable_scope('conv1') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 7, FLAGS.alphabet_length + 1, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(sequences, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv1)
# pool1
pool1 = tf.nn.max_pool(conv1,
ksize=[1, 1, 3, 1],
strides=[1, 1, 3, 1],
padding='SAME',
name='pool1')
# conv2
with tf.variable_scope('conv2') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 7, FEATURE_NUM, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv2)
# pool2
pool2 = tf.nn.max_pool(conv2,
ksize=[1, 1, 3, 1],
strides=[1, 1, 3, 1],
padding='SAME',
name='pool2')
# conv3
with tf.variable_scope('conv3') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 3, FEATURE_NUM, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(pool2, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv3)
# conv4
with tf.variable_scope('conv4') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 3, FEATURE_NUM, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv4)
# conv5
with tf.variable_scope('conv5') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 3, FEATURE_NUM, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv5)
# conv6
with tf.variable_scope('conv6') as scope:
kernel = _variable_with_weight_decay(
'weights',
shape=[1, 3, FEATURE_NUM, FEATURE_NUM],
stddev=0.02,
wd=None)
conv = tf.nn.conv2d(conv5, kernel, [1, 1, 1, 1], padding='SAME')
biases = _variable_on_cpu('biases', [FEATURE_NUM],
tf.constant_initializer(0.02))
bias = tf.nn.bias_add(conv, biases)
conv6 = tf.nn.relu(bias, name=scope.name)
_activation_summary(conv6)
# pool6
pool6 = tf.nn.max_pool(conv6,
ksize=[1, 1, 3, 1],
strides=[1, 1, 3, 1],
padding='SAME',
name='pool6')
# local7
with tf.variable_scope('local7') as scope:
# Move everything into depth so we can perform a single matrix multiply.
reshape = tf.reshape(pool6, [FLAGS.minibatch_size, -1])
dim = reshape.get_shape()[1].value
weights = _variable_with_weight_decay('weights',
shape=[dim, 1024],
stddev=0.02,
wd=None)
biases = _variable_on_cpu('biases', [1024],
tf.constant_initializer(0.02))
local7 = tf.nn.relu(
tf.matmul(reshape, weights) + biases,
name=scope.name)
_activation_summary(local7)
# dropout7
dropout7 = tf.nn.dropout(local7, FLAGS.dropout_keep_prob, name="dropout7")
# local8
with tf.variable_scope('local8') as scope:
weights = _variable_with_weight_decay('weights',
shape=[1024, 1024],
stddev=0.02,
wd=None)
biases = _variable_on_cpu('biases', [1024],
tf.constant_initializer(0.02))
local8 = tf.nn.relu(
tf.matmul(dropout7, weights) + biases,
name=scope.name)
_activation_summary(local8)
# dropout8
dropout8 = tf.nn.dropout(local8, FLAGS.dropout_keep_prob, name="dropout8")
# softmax, i.e. softmax(WX + b)
with tf.variable_scope('softmax_linear') as scope:
print ("NUM_CLASSES:", NUM_CLASSES)
weights = _variable_with_weight_decay('weights',
[1024, NUM_CLASSES],
stddev=0.02,
wd=None)
biases = _variable_on_cpu('biases', [NUM_CLASSES],
tf.constant_initializer(0.02))
softmax_linear = tf.add(
tf.matmul(dropout8, weights),
biases,
name=scope.name)
_activation_summary(softmax_linear)
return softmax_linear
def loss(logits, labels):
"""Add L2Loss to all the trainable variables.
Add summary for "Loss" and "Loss/avg".
Args:
logits: Logits from inference().
labels: Labels from distorted_inputs or inputs(). 1-D tensor
of shape [batch_size]
Returns:
Loss tensor of type float.
"""
# Calculate the average cross entropy loss across the batch.
labels = tf.cast(labels, tf.int64)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits,
labels,
name='cross_entropy_per_example')
cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
tf.add_to_collection('losses', cross_entropy_mean)
# The total loss is defined as the cross entropy loss plus all of the weight
# decay terms (L2 loss).
return tf.add_n(tf.get_collection('losses'), name='total_loss')
def _add_loss_summaries(total_loss):
"""Add summaries for losses in CNN model.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of losses.
"""
# Compute the moving average of all individual losses and the total loss.
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')
losses = tf.get_collection('losses')
loss_averages_op = loss_averages.apply(losses + [total_loss])
# Attach a scalar summary to all individual losses and the total loss; do the
# same for the averaged version of the losses.
for l in losses + [total_loss]:
# Name each loss as '(raw)' and name the moving average version of the loss
# as the original loss name.
tf.scalar_summary(l.op.name + ' (raw)', l)
tf.scalar_summary(l.op.name, loss_averages.average(l))
return loss_averages_op
def training(total_loss, global_step):
"""Train CNN model.
Create an optimizer and apply to all trainable variables. Add moving
average for all trainable variables.
Args:
total_loss: Total loss from loss().
global_step: Integer Variable counting the number of training steps
processed.
Returns:
train_op: op for training.
"""
# Variables that affect learning rate.
num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.minibatch_size
decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)
# Decay the learning rate exponentially based on the number of steps.
lr_decay = tf.train.exponential_decay(INITIAL_LEARNING_RATE,
global_step,
decay_steps,
LEARNING_RATE_DECAY_FACTOR,
staircase=True)
# compare with 0.01 * 0.5^10
lr = tf.maximum(lr_decay, 0.000009765625)
tf.scalar_summary('learning_rate', lr)
# Generate moving averages of all losses and associated summaries.
loss_averages_op = _add_loss_summaries(total_loss)
# Compute gradients.
with tf.control_dependencies([loss_averages_op]):
# opt = tf.train.GradientDescentOptimizer(lr)
opt = tf.train.MomentumOptimizer(lr, 0.9)
grads = opt.compute_gradients(total_loss)
# Apply gradients.
apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)
# Add histograms for trainable variables.
for var in tf.trainable_variables():
tf.histogram_summary(var.op.name, var)
# Add histograms for gradients.
for grad, var in grads:
if grad is not None:
tf.histogram_summary(var.op.name + '/gradients', grad)
# # Track the moving averages of all trainable variables.
# variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,
# global_step)
# variables_averages_op = variable_averages.apply(tf.trainable_variables())
with tf.control_dependencies([apply_gradient_op]):
train_op = tf.no_op(name='train')
return train_op | cnn_character/model.py | [
"Gaussian"
] | 55a9e5eca84025b8f913a86037539b4f0319619e7367c31fd22052fefd0627df |
# Leaflet - Quickstart
This project is intended to make it easier to start up a new mapping application
using Leaflet.
See the [style guide](https://github.com/consbio/leaflet-quickstart/blob/master/docs/style_guide.md) to use for developing these applications.
## Intended audience
Software developers with the Conservation Biology Institute, developing client-facing
mapping applications.
## Work in progress!
Pretty much anything is subject to change at this point.
## Setup
Run `npm install` to pull down required dependencies after you checkout this project.
## Build process
This project uses Gulp to minify and concatenate CSS and JS files.
Run `gulp build` to run the build, which produces artifacts in `static/dist`.
Run `gulp` to run gulp watch and update built files after you change the sources.
## Core Dependencies
* Leaflet (1.0b2)
* Leaflet Omnivore
* D3
* Lodash
* Font Awesome
* [Leaflet.ZoomBox](https://github.com/consbio/Leaflet.ZoomBox)
* [Leaflet.Geonames](https://github.com/consbio/Leaflet.Geonames)
* [Leaflet.Basemaps](https://github.com/consbio/Leaflet.Basemaps)
| README.md | [
"GULP"
] | 562da0242fc86e343b63c60ad6822e3f750d677d5ede69b47101b3f05f884df4 |
#######################
# Reference
#######################
reference:
# Whether to generate a reference matrix from scratch
# 1 to generate, 0 to use an existing matrix (a SCE object saved as an RDS object)
generate: 1
# Path and file name of reference RDS if not generated by the pipeline.
# SCE object with cell type listed in column named "label"
path: reference_sce.rds
# Type of reference to use:
# celldex
# scRNAseq
package: celldex
# Name of celldex reference database:
# http://bioconductor.org/packages/release/data/experiment/vignettes/celldex/inst/doc/userguide.html
# HumanPrimaryCellAtlasData
# BlueprintEncodeData
# MouseRNAseqData
# ImmGenData
# DatabaseImmuneCellExpressionData
# NovershternHematopoieticData
# MonacoImmuneData
celldex_reference_name: HumanPrimaryCellAtlasData
# scRNAseq package references:
# https://bioconductor.org/packages/devel/data/experiment/vignettes/scRNAseq/inst/doc/scRNAseq.html#available-data-sets
# Name of reference without the brackets. Some databases are not labelled.
scRNAseq_reference_name: BaronPancreasData
# Options for scRNAseq reference, e.g. 'human', 'mouse' etc.
# Leave blank for no option
scRNAseq_option:
#######################
# Seurat markers
#######################
# run seurat markers
markerdiff: 0
markers:
# Path to metadata file. First column sample_name, other columns specified by user
meta_data: metadata.csv
# Group to compare across e.g. stim, treated etc.
group: stim
# Conditions in stim to compare, separated with "_v_". Multiple comparisons separated with space
DE_versus: cntrl_v_drug1 cntrl_v_drug2
# List of pre-defined markers. Separate genes by underscore e.g. ENSG00000081237_ENSG00000090339_ENSG00000139193
predefined_list: ENSG00000081237_ENSG00000090339_ENSG00000139193
#######################
# SingleR
#######################
singler:
# Whether to run singleR annotation or not.
# 0 or 1
run: 1
# Option to perform wilcoxin test to identify top markers for each pairwise comparison between labels
# Slower but more appropriate for sc data compared to just default algorithm
# 0 or 1, 0 not to run, 1 to run
DEmethod: 0
# SingleR method, annotate by cell (single) or by cluster. Default = single. Options:
# single
# cluster
method: single
#######################
# clustifyr
#######################
clustifyr:
# Whether to run clustifyr annotation or not.
# 0 or 1
run: 1
# Dimension reduction to annotate, options:
# umap
# tsne
# pca
dimRed: umap
# Whether to run clustifyr using variable features or not. 0 or 1
var_features: 1
#######################
# scClassify
#######################
scclassify:
# Whether to run scClassify or not.
# 0 or 1
run: 1
# Whether to use pretrained model
# 0 for no
# or path to rds file of pretrained scClassifyTrainModel or scClassifyTrainModelList
# Download links from package github: https://github.com/SydneyBioX/scClassify
pretrained: 0
# Which scClassify method to use.
# Predict uses a model pre-built in programme or in dir. Train: train and test model in one step
# If method is set to train, pretrained will be set to 0
# Options:
# predict
# train
method: predict
# What similarity metrics to use. List separated by single space. Options:
# pearson
# spearman
# cosine
# jaccard
# kendall
# weighted rank
# manhattan
similarity: pearson spearman | scpipelines/seurat/pipeline_annotation-6/pipeline.yml | [
"Bioconductor"
] | e036ea91ccceea3cd83edaf59433746570557ed47ccd6b519f1ee790cc053c36 |
const isDev = process.env.NODE_ENV === 'development'
module.exports = {
siteMetadata: {
title: `Inkdrop`,
description: `The Note-Taking App with Robust Markdown Editor`,
author: `@inkdrop_app`
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`
}
},
`gatsby-transformer-sharp`,
{
resolve: `gatsby-plugin-sharp`,
options: {
defaultQuality: 70
}
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/favicon.png` // This path is relative to the root of the site.
}
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
`gatsby-plugin-less`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `release-pages`,
path: `${__dirname}/src/pages`
}
},
{
resolve: `gatsby-transformer-yaml`,
options: {
typeName: `Yaml`
}
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/data/`
}
},
{
resolve: 'gatsby-plugin-fathom',
options: {
siteId: 'KOOITLXG',
honorDnt: true
}
},
{
resolve: `gatsby-plugin-purgecss`,
options: {
printRejected: true, // Print removed selectors and processed file names
// develop: true, // Enable while using `gatsby develop`
// tailwind: true, // Enable tailwindcss support
// whitelist: ['whitelist'], // Don't remove this selector
ignore: ['src/components/', 'flickity/']
// purgeOnly : ['components/', '/main.css', 'bootstrap/'], // Purge only these files/folders
}
},
'gatsby-plugin-svgr',
{
resolve: `gatsby-plugin-csp`,
options: {
disableOnDev: false,
reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
mergeScriptHashes: false, // you can disable scripts sha256 hashes
mergeStyleHashes: false, // you can disable styles sha256 hashes
mergeDefaultDirectives: true,
directives: {
'script-src': `'self' 'unsafe-inline' *.inkdrop.app *.usefathom.com${
isDev ? " 'unsafe-eval'" : ''
}`,
'style-src':
"'self' 'unsafe-inline' *.inkdrop.app fonts.googleapis.com",
'img-src':
"'self' data: *.inkdrop.app *.usefathom.com stats.g.doubleclick.net *.medium.com",
'media-src': "'self' *.inkdrop.app",
'font-src': "'self' data: fonts.gstatic.com",
'frame-src': 'www.youtube.com',
'connect-src': `'self' api.inkdrop.app *.usefathom.com stats.g.doubleclick.net ${
isDev ? ' localhost:* ws://localhost:*' : ''
}`
}
}
}
]
} | gatsby-config.js | [
"VisIt"
] | 63c6697eb7dfe85c870d652647e5acbc74b1f0575a780a8c93c40cd46d1d08c1 |
import { Construct } from 'constructs';
import * as cdktf from 'cdktf';
/**
* Amazon Chime
*/
export interface ChimeVoiceConnectorTerminationCredentialsConfig extends cdktf.TerraformMetaArguments {
/**
* Docs at Terraform Registry: {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials#voice_connector_id ChimeVoiceConnectorTerminationCredentials#voice_connector_id}
*/
readonly voiceConnectorId: string;
/**
* credentials block
*
* Docs at Terraform Registry: {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials#credentials ChimeVoiceConnectorTerminationCredentials#credentials}
*/
readonly credentials: ChimeVoiceConnectorTerminationCredentialsCredentials[] | cdktf.IResolvable;
}
export interface ChimeVoiceConnectorTerminationCredentialsCredentials {
/**
* Docs at Terraform Registry: {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials#password ChimeVoiceConnectorTerminationCredentials#password}
*/
readonly password: string;
/**
* Docs at Terraform Registry: {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials#username ChimeVoiceConnectorTerminationCredentials#username}
*/
readonly username: string;
}
export function chimeVoiceConnectorTerminationCredentialsCredentialsToTerraform(struct?: ChimeVoiceConnectorTerminationCredentialsCredentials | cdktf.IResolvable): any {
if (!cdktf.canInspect(struct) || cdktf.Tokenization.isResolvable(struct)) { return struct; }
if (cdktf.isComplexElement(struct)) {
throw new Error("A complex element was used as configuration, this is not supported: https://cdk.tf/complex-object-as-configuration");
}
return {
password: cdktf.stringToTerraform(struct!.password),
username: cdktf.stringToTerraform(struct!.username),
}
}
/**
* Represents a {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials aws_chime_voice_connector_termination_credentials}
*/
export class ChimeVoiceConnectorTerminationCredentials extends cdktf.TerraformResource {
// =================
// STATIC PROPERTIES
// =================
public static readonly tfResourceType: string = "aws_chime_voice_connector_termination_credentials";
// ===========
// INITIALIZER
// ===========
/**
* Create a new {@link https://www.terraform.io/docs/providers/aws/r/chime_voice_connector_termination_credentials aws_chime_voice_connector_termination_credentials} Resource
*
* @param scope The scope in which to define this construct
* @param id The scoped construct ID. Must be unique amongst siblings in the same scope
* @param options ChimeVoiceConnectorTerminationCredentialsConfig
*/
public constructor(scope: Construct, id: string, config: ChimeVoiceConnectorTerminationCredentialsConfig) {
super(scope, id, {
terraformResourceType: 'aws_chime_voice_connector_termination_credentials',
terraformGeneratorMetadata: {
providerName: 'aws'
},
provider: config.provider,
dependsOn: config.dependsOn,
count: config.count,
lifecycle: config.lifecycle
});
this._voiceConnectorId = config.voiceConnectorId;
this._credentials = config.credentials;
}
// ==========
// ATTRIBUTES
// ==========
// id - computed: true, optional: true, required: false
public get id() {
return this.getStringAttribute('id');
}
// voice_connector_id - computed: false, optional: false, required: true
private _voiceConnectorId?: string;
public get voiceConnectorId() {
return this.getStringAttribute('voice_connector_id');
}
public set voiceConnectorId(value: string) {
this._voiceConnectorId = value;
}
// Temporarily expose input value. Use with caution.
public get voiceConnectorIdInput() {
return this._voiceConnectorId;
}
// credentials - computed: false, optional: false, required: true
private _credentials?: ChimeVoiceConnectorTerminationCredentialsCredentials[] | cdktf.IResolvable;
public get credentials() {
// Getting the computed value is not yet implemented
return cdktf.Token.asAny(cdktf.Fn.tolist(this.interpolationForAttribute('credentials')));
}
public set credentials(value: ChimeVoiceConnectorTerminationCredentialsCredentials[] | cdktf.IResolvable) {
this._credentials = value;
}
// Temporarily expose input value. Use with caution.
public get credentialsInput() {
return this._credentials;
}
// =========
// SYNTHESIS
// =========
protected synthesizeAttributes(): { [name: string]: any } {
return {
voice_connector_id: cdktf.stringToTerraform(this._voiceConnectorId),
credentials: cdktf.listMapper(chimeVoiceConnectorTerminationCredentialsCredentialsToTerraform)(this._credentials),
};
}
} | @types/providers/aws/chime/chime-voice-connector-termination-credentials.ts | [
"CDK"
] | 319adf1185132d3ee4dadabddc3096f3c01474ba9e1b108dd19882b7ec4c631a |
# PowerAuth Mobile SDK for Android
<!-- begin remove -->
## Table of Contents
- [SDK Installation](#installation)
- [SDK Configuration](#configuration)
- [Device Activation](#activation)
- [Activation via Activation Code](#activation-via-activation-code)
- [Activation via Custom Credentials](#activation-via-custom-credentials)
- [Activation via Recovery Code](#activation-via-recovery-code)
- [Customize Activation](#customize-activation)
- [Committing Activation Data](#committing-activation-data)
- [Validating User Inputs](#validating-user-inputs)
- [Requesting Device Activation Status](#requesting-activation-status)
- [Data Signing](#data-signing)
- [Symmetric Multi-Factor Signature](#symmetric-multi-factor-signature)
- [Asymmetric Private Key Signature](#asymmetric-private-key-signature)
- [Symmetric Offline Multi-Factor Signature](#symmetric-offline-multi-factor-signature)
- [Verify Server-Signed Data](#verify-server-signed-data)
- [Password Change](#password-change)
- [Biometric Authentication Setup](#biometric-authentication-setup)
- [Device Activation Removal](#activation-removal)
- [End-To-End Encryption](#end-to-end-encryption)
- [Secure Vault](#secure-vault)
- [Recovery Codes](#recovery-codes)
- [Getting Recovery Data](#getting-recovery-data)
- [Confirm Recovery Postcard](#confirm-recovery-postcard)
- [Token-Based Authentication](#token-based-authentication)
- [Common SDK Tasks](#common-sdk-tasks)
- [Additional Features](#additional-features)
- [Password Strength Indicator](#password-strength-indicator)
- [Debug Build Detection](#debug-build-detection)
- [Request Interceptors](#request-interceptors)
<!-- end -->
## Installation
To get PowerAuth SDK for Android up and running in your app, add the following dependency in your `gradle.build` file:
```gradle
repositories {
mavenCentral() // if not defined elsewhere...
}
dependencies {
compile 'com.wultra.android.powerauth:powerauth-sdk:1.x.y'
}
```
Note that this documentation is using version `1.x.y` as an example. You can find the latest version in our [List of Releases](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Releases.md). The Android Studio IDE can also find and offer updates for your application's dependencies.
From now on, you can use `PowerAuthSDK` class in your project.
To use development version, you need to install it in your local Maven repository and make this repository available to your Gradle script.
```sh
$ git clone --recurse-submodules https://github.com/wultra/powerauth-mobile-sdk.git
$ cd powerauth-mobile-sdk/proj-android
$ sh build-publish-local.sh
```
In your Gradle script:
```gradle
apply plugin: "maven"
repositories {
mavenLocal()
}
```
You also need to install base Java modules in your maven repository:
```sh
$ git clone --recurse-submodules https://github.com/wultra/powerauth-restful-integration.git
$ cd powerauth-restful-integration
$ mvn clean install -DskipTests=true
```
## Configuration
In order to be able to configure your `PowerAuthSDK` instance, you need the following values from the PowerAuth Server:
- `APP_KEY` - Application key that binds activation with a specific application.
- `APP_SECRET` - Application secret that binds activation with a specific application.
- `KEY_MASTER_SERVER_PUBLIC` - Master Server Public Key, used for non-personalized encryption and server signature verification.
You also need to specify your instance ID (by default, this can be for example an app package name). This is because one application may use more than one custom instance of `PowerAuthSDK`, and the identifier is the way to distinguish these instances while working with Keychain data.
Finally, you need to know the location of your [PowerAuth Standard RESTful API](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Standard-RESTful-API.md) endpoints. That path should contain everything that goes before the `/pa/**` prefix of the API endpoints.
To sum it up, in order to configure the `PowerAuthSDK` default instance, add the following code to your application main activity `onCreate()` method:
```java
String INSTANCE_ID = getApplicationContext().getPackageName();
String PA_APPLICATION_KEY = "<KEY>;
String PA_APPLICATION_SECRET = "<KEY>;
String PA_MASTER_SERVER_PUBLIC_KEY = "<KEY>;
String API_SERVER = "https://localhost:8080/demo-server";
try {
final PowerAuthConfiguration configuration = new PowerAuthConfiguration.Builder(
INSTANCE_ID,
API_SERVER,
PA_APPLICATION_KEY,
PA_APPLICATION_SECRET,
PA_MASTER_SERVER_PUBLIC_KEY)
.build();
PowerAuthSDK powerAuthSDK = new PowerAuthSDK.Builder(configuration)
.build(getApplicationContext());
} catch (PowerAuthErrorException e) {
// Failed to construct `PowerAuthSDK` due to insufficient keychain protection.
// (See next chapter for details)
}
```
### Activation Data Protection
By default, the PowerAuth Mobile SDK for Android encrypts the local activation data with a symmetric key generated by the Android KeyStore on the Android 6 and newer devices. On older devices, or if the device has an unreliable KeyStore implementation, then the fallback to unencrypted storage, based on private [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) is used. If your application requires a higher level of activation data protection, then you can enforce the level of protection in `PowerAuthKeychainConfiguration`:
```java
try {
PowerAuthKeychainConfiguration keychainConfig = new PowerAuthKeychainConfiguration.Builder()
.minimalRequiredKeychainProtection(KeychainProtection.HARDWARE)
.build();
// Apply keychain configuration
PowerAuthSDK powerAuthSDK = new PowerAuthSDK.Builder(configuration)
.keychainConfiguration(keychainConfig)
.build(getApplicationContext());
} catch (PowerAuthErrorException e) {
// Failed to construct `PowerAuthSDK` due to insufficient keychain protection.
}
```
You can also determine the level of keychain protection before `PowerAuthSDK` object creation by calling:
```java
@KeychainProtection int keychainProtectionLevel = KeychainFactory.getKeychainProtectionSupportedOnDevice(context));
```
The following levels of keychain protection are defined:
- `NONE` - The content of the keychain is not encrypted and therefore not protected. This level of the protection is typically reported on devices older than Android Marshmallow, or in case that the device has faulty KeyStore implementation.
- `SOFTWARE` - The content of the keychain is encrypted with key generated by Android KeyStore, but the key is protected only on the operating system level. The security of the key material relies solely on software measures, which means that a compromise of the Android OS (such as root exploit) might up revealing this key.
- `HARDWARE` - The content of the keychain is encrypted with key generated by Android KeyStore and the key is stored and managed by [Trusted Execution Environment](https://en.wikipedia.org/wiki/Trusted_execution_environment).
- `STRONGBOX` - The content of the keychain is encrypted with key generated by Android KeyStore and the key is stored inside of Secure Element (e.g. StrongBox). This is the highest level of Keychain protection currently available, but not enabled by default. See [note below](#strongbox-support-note).
Be aware, that enforcing the required level of protection must be properly reflected in your application's user interface. That means that you should inform the user in case that the device has an insufficient capabilities to run your application securely.
#### StrongBox Support Note
The StrongBox backed keys are by default turned-off due to poor reliability and low performance of StrongBox implementations on the current Android devices. If you want to turn support on in your application, then use the following code at your application's startup:
```java
try {
KeychainFactory.setStrongBoxEnabled(context, true);
} catch (PowerAuthErrorException e) {
// You must alter the configuration before any keychain is accessed.
// Basically, you should not create any PowerAuthSDK instance before the change.
}
```
## Activation
After you configure the SDK instance, you are ready to make your first activation.
### Activation via Activation Code
The original activation method uses a one-time activation code generated in PowerAuth Server. To create an activation using this method, some external application (Internet banking, ATM application, branch / kiosk application) must generate an activation code for you and display it (as a text or in a QR code).
In case you would like to use QR code scanning to enter an activation code, you can use any library of your choice, for example [Barcode Scanner](https://github.com/dm77/barcodescanner) open-source library based on ZBar lib.
Use the following code to create an activation once you have an activation code:
```java
String deviceName = "<NAME>";
String activationCode = "VVVVV-VVVVV-VVVVV-VTFVA"; // let user type or QR-scan this value
// Create activation object with given activation code.
final PowerAuthActivation activation;
try {
activation = PowerAuthActivation.Builder.activation(activationCode, deviceName).build();
} catch (PowerAuthErrorException e) {
// Invalid activation code
}
// Create a new activation with given activation object
powerAuthSDK.createActivation(activation, new ICreateActivationListener() {
@Override
public void onActivationCreateSucceed(CreateActivationResult result) {
final String fingerprint = result.getActivationFingerprint();
final RecoveryData activationRecovery = result.getRecoveryData();
// No error occurred, proceed to credentials entry (PIN prompt, Enable "Fingerprint Authentication" switch, ...) and commit
// The 'fingerprint' value represents the combination of device and server public keys - it may be used as visual confirmation
// If server supports recovery codes for activation, then `activationRecovery` contains object with information about activation recovery.
}
@Override
public void onActivationCreateFailed(Throwable t) {
// Error occurred, report it to the user
}
});
```
If the received activation result also contains recovery data, then you should display that values to the user. To do that, please read the [Getting Recovery Data](#getting-recovery-data) section of this document, which describes how to treat that sensitive information. This is relevant for all types of activation you use.
#### Additional Activation OTP
If an [additional activation OTP](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Additional-Activation-OTP.md) is required to complete the activation, then use the following code to configure the `PowerAuthActivation` object:
```java
String deviceName = "Petr's iPhone 7" // or UIDevice.current.name
String activationCode = "VVVVV-VVVVV-VVVVV-VTFVA" // let user type or QR-scan this value
String activationOtp = "12345"
// Create activation object with given activation code and OTP.
final PowerAuthActivation activation;
try {
activation = PowerAuthActivation.Builder.activation(activationCode, deviceName)
.setAdditionalActivationOtp(activationOtp)
.build();
} catch (PowerAuthErrorException e) {
// Invalid activation code
}
// The rest of the activation routine is the same.
```
<!-- begin box warning -->
Be aware that OTP can be used only if the activation is configured for ON_KEY_EXCHANGE validation on the PowerAuth server. See our [crypto documentation for details](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Additional-Activation-OTP.md#regular-activation-with-otp).
<!-- end -->
### Activation via Custom Credentials
You may also create an activation using any custom login data - it can be anything that the server can use to obtain the user ID to associate with a new activation. Since the credentials are custom, the server's implementation must be able to process such a request. Unlike the previous versions of SDK, the custom activation no longer requires a custom activation endpoint.
Use the following code to create an activation using custom credentials:
```java
// Create a new activation with a given device name and login credentials
String deviceName = "Juraj's JiaYu S3";
Map<String, String> credentials = new HashMap<>();
credentials.put("username", "<EMAIL>");
credentials.put("password", "<PASSWORD>");
// Create activation object with given credentials.
final PowerAuthActivation activation;
try {
activation = PowerAuthActivation.Builder.customActivation(credentials, deviceName).build();
} catch (PowerAuthErrorException e) {
// Credentials dictionary is empty
}
// Create a new activation with given activation object
powerAuthSDK.createActivation(activation, new ICreateActivationListener() {
@Override
public void onActivationCreateSucceed(CreateActivationResult result) {
final String fingerprint = result.getActivationFingerprint();
final RecoveryData activationRecovery = result.getRecoveryData();
// No error occurred, proceed to credentials entry (PIN prompt, Enable "Biometric Authentication" switch, ...) and commit
// The 'fingerprint' value represents the combination of device and server public keys - it may be used as visual confirmation
// If server supports recovery codes for activation, then `activationRecovery` contains object with information about activation recovery.
}
@Override
public void onActivationCreateFailed(Throwable t) {
// Error occurred, report it to the user
}
});
```
Note that by using weak identity attributes to create an activation, the resulting activation is confirming a "blurry identity". This may greatly limit the legal weight and usability of a signature. We recommend using a strong identity verification before activation can actually be created.
### Activation via Recovery Code
If PowerAuth Server is configured to support [Recovery Codes](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Activation-Recovery.md), then also you can create an activation via the recovery code and PUK.
Use the following code to create an activation using recovery code:
```java
final String deviceName = "<NAME>"
final String recoveryCode = "55555-55555-55555-55YMA" // User's input
final String puk = "0123456789" // User's input. You should validate RC & PUK with using ActivationCodeUtil
// Create activation object with given recovery code and PUK.
final PowerAuthActivation activation;
try {
activation = PowerAuthActivation.Builder.recoveryActivation(recoveryCode, puk, deviceName).build();
} catch (PowerAuthErrorException e) {
// Invalid recovery code or PUK
}
// Create a new activation with given activation object
powerAuthSDK.createActivation(activation, new ICreateActivationListener() {
@Override
public void onActivationCreateSucceed(CreateActivationResult result) {
final String fingerprint = result.getActivationFingerprint();
final RecoveryData activationRecovery = result.getRecoveryData();
// No error occurred, proceed to credentials entry (PIN prompt, Enable "Biometric Authentication" switch, ...) and commit
// The 'fingerprint' value represents the combination of device and server public keys - it may be used as visual confirmation
// If server supports recovery codes for activation, then `activationRecovery` contains object with information about activation recovery.
}
@Override
public void onActivationCreateFailed(Throwable t) {
// Error occurred, report it to the user
// On top of a regular error processing, you should handle a special situation, when server gives an additional information
// about which PUK must be used for the recovery. The information is valid only when recovery code from a postcard is applied.
if (t instanceof ErrorResponseApiException) {
ErrorResponseApiException exception = (ErrorResponseApiException) t;
Error errorResponse = exception.getErrorResponse();
int currentRecoveryPukIndex = errorResponse.getCurrentRecoveryPukIndex();
if (currentRecoveryPukIndex > 0) {
// The PUK index is known, you should inform user that it has to rewrite PUK from a specific position.
}
}
}
});
```
### Customize Activation
You can set an additional properties to `PowerAuthActivation` object, before any type of activation is created. For example:
```java
String deviceName = "<NAME>";
String activationCode = "VVVVV-VVVVV-VVVVV-VTFVA"; // let user type or QR-scan this value
// Custom attributes that can be processed before the activation is created on PowerAuth Server.
// The dictionary may contain only values that can be serialized to JSON.
List<String> otherIds = new ArrayList<>();
otherIds.add("e43f5f99-e2e9-49f2-bcae-5e32a5e96d22");
otherIds.add("41dd704c-65e6-4d4b-b28f-0bc0e4eb9715");
Map<String, Object> customAttributes = new HashMap<>();
customAttributes.put("isPrimaryActivation", true);
customAttributes.put("otherActivationIds", otherIds);
// Extra flags that will be associated with the activation record on PowerAuth Server.
String extraFlags = "EXTRA_FLAGS"
// Now create the activation object with all that extra data
final PowerAuthActivation activation;
try {
activation = PowerAuthActivation.Builder.activation(activationCode, deviceName)
.setCustomAttributes(customAttributes)
.setExtras(extras)
.build();
} catch (PowerAuthErrorException e) {
// Invalid activation code
}
// The rest of the activation routine is the same.
}
```
### Committing Activation Data
After you create an activation using one of the methods mentioned above, you need to commit the activation - to use provided user credentials to store the activation data on the device. Use the following code to do this.
```java
// Commit activation using given PIN
int result = powerAuthSDK.commitActivationWithPassword(context, pin);
if (result != PowerAuthErrorCodes.SUCCEED) {
// happens only in case SDK was not configured or activation is not in state to be committed
}
```
This code has created activation with two factors: possession (key stored using a key derived from a device fingerprint) and knowledge (password, in our case, a simple PIN code). If you would like to enable biometric authentication support at this moment, use the following code instead of the one above:
```java
// Commit activation using given PIN and ad-hoc generated biometric related key
powerAuthSDK.commitActivation(context, fragment, "Enable Biometric Authentication", "To enable biometric authentication, use the biometric sensor on your device.", pin, new ICommitActivationWithBiometryListener() {
@Override
public void onBiometricDialogCancelled() {
// Biometric enrolment cancelled by user
}
@Override
public void onBiometricDialogSuccess() {
// success, activation has been committed
}
@Override
public void onBiometricDialogFailed(@NonNull PowerAuthErrorException error) {
// failure, typically as a result of API misuse, or a biometric authentication failure
}
});
```
Also, you can use the following code to create activation with the best granularity control:
```java
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = encryptedBiometryKey;
int result = powerAuthSDK.commitActivationWithAuthentication(context, authentication);
if (result != PowerAuthErrorCodes.SUCCEED) {
// happens only in case SDK was not configured or activation is not in state to be committed
}
```
Note that you currently need to obtain the encrypted biometry key yourself - you have to use `BiometricPrompt.CryptoObject` or integration with Android `KeyStore` to do so.
### Validating User Inputs
The mobile SDK is providing a couple of functions in `ActivationCodeUtil` class, helping with user input validation. You can:
- Parse activation code when it's scanned from QR code
- Validate a whole code at once
- Validate recovery code or PUK
- Auto-correct characters typed on the fly
#### Validating Scanned QR Code
To validate an activation code scanned from QR code, you can use `ActivationCodeUtil.parseFromActivationCode()` function. You have to provide the code with or without the signature part. For example:
```java
final String scannedCode = "VVVVV-VVVVV-VVVVV-VTFVA#aGVsbG8.....gd29ybGQ=";
final ActivationCode code = ActivationCodeUtil.parseFromActivationCode(scannedCode);
if (code == null || code.activationCode == null) {
// Invalid code, QR code should contain a signature
return;
}
```
Note that the signature is only formally validated in the function above. The actual signature verification is done in the activation process, or you can do it on your own:
```java
final String scannedCode = "VVVVV-VVVVV-VVVVV-VTFVA#aGVsbG8......gd29ybGQ=";
final ActivationCode code = ActivationCodeUtil.parseFromActivationCode(scannedCode);
if (code == null || code.activationCode == null) {
return;
}
final byte[] codeBytes = code.activationCode.getBytes(Charset.defaultCharset());
final byte[] signatureBytes = Base64.decode(code.activationSignature, Base64.NO_WRAP);
if (!powerAuthSDK.verifyServerSignedData(codeBytes, signatureBytes, true)) {
// Invalid signature
}
```
#### Validating Entered Activation Code
To validate an activation code at once, you can call `ActivationCodeUtil.validateActivationCode()` function. You have to provide the code without the signature part. For example:
```java
boolean isValid = ActivationCodeUtil.validateActivationCode("VVVVV-VVVVV-VVVVV-VTFVA");
boolean isInvalid = ActivationCodeUtil.validateActivationCode("VVVVV-VVVVV-VVVVV-VTFVA#aGVsbG8gd29ybGQ=");
```
If your application is using your own validation, then you should switch to functions provided by SDK. The reason for that is that since SDK `1.0.0`, all activation codes contain a checksum, so it's possible to detect mistyped characters before you start the activation. Check our [Activation Code](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Activation-Code.md) documentation for more details.
#### Validating Recovery Code and PUK
To validate a recovery code at once, you can call `ActivationCodeUtil.validateRecoveryCode()` function. You can provide the whole code, which may or may not contain `"R:"` prefix. So, you can validate manually entered codes, but also codes scanned from QR. For example:
```java
boolean isValid1 = ActivationCodeUtil.validateRecoveryCode("VVVVV-VVVVV-VVVVV-VTFVA");
boolean isValid2 = ActivationCodeUtil.validateRecoveryCode("R:VVVVV-VVVVV-VVVVV-VTFVA");
```
To validate PUK at once, you can call `ActivationCodeUtil.validateRecoveryPuk()` function:
```java
boolean isValid = ActivationCodeUtil.validateRecoveryPuk("0123456789");
```
#### Auto-Correcting Typed Characters
You can implement auto-correcting of typed characters with using `ActivationCodeUtil.validateAndCorrectTypedCharacter()` function in screens, where user is supposed to enter an activation or recovery code. This technique is possible due to the fact that Base32 is constructed so that it doesn't contain visually confusing characters. For example, `1` (number one) and `I` (capital I) are confusing, so only `I` is allowed. The benefit is that the provided function can correct typed `1` and translate it to `I`.
Here's an example how to iterate over the string and validate it character by character:
```java
/// Returns corrected character or null in case of error.
@Nullable String validateTypedCharacters(@NonNull String input) {
final int length = input.length();
final StringBuilder output = new StringBuilder(length);
for (int offset = 0; offset < length; ) {
final int codepoint = input.codePointAt(offset);
offset += Character.charCount(codepoint);
final int corrected = ActivationCodeUtil.validateAndCorrectTypedCharacter(codepoint);
if (corrected == 0) {
return null;
}
// Character.isBmpCodePoint(corrected) is always true
output.append((char)corrected);
}
return output.toString();
}
// validateTypedCharacter("v1") == "VI"
// validateTypedCharacter("9") == null
```
## Requesting Activation Status
To obtain a detailed activation status information, use the following code:
```java
// Check if there is some activation on the device
if (powerAuthSDK.hasValidActivation()) {
// If there is an activation on the device, check the status with server
powerAuthSDK.fetchActivationStatusWithCallback(context, new IActivationStatusListener() {
@Override
public void onActivationStatusSucceed(ActivationStatus status) {
// Activation state: State_Created, State_Pending_Commit, State_Active, State_Blocked, State_Removed, State_Deadlock
switch (status.state) {
case ActivationStatus.State_Pending_Commit:
// Activation is awaiting commit on the server.
android.util.Log.i(TAG, "Waiting for commit");
break;
case ActivationStatus.State_Active:
// Activation is valid and active.
android.util.Log.i(TAG, "Activation is active");
break;
case ActivationStatus.State_Blocked:
// Activation is blocked. You can display unblock
// instructions to the user.
android.util.Log.i(TAG, "Activation is blocked");
break;
case ActivationStatus.State_Removed:
// Activation is no longer valid on the server.
// You can inform user about this situation and remove
// activation locally.
android.util.Log.i(TAG, "Activation is no longer valid");
powerAuthSDK.removeActivationLocal(context);
break;
case ActivationStatus.State_Deadlock:
// Local activation is technically blocked and no longer
// can be used for the signature calculations. You can inform
// user about this situation and remove activation locally.
android.util.Log.i(TAG, "Activation is technically blocked");
powerAuthSDK.removeActivationLocal(context);
break;
case ActivationStatus.State_Created:
// Activation is just created. This is the internal
// state on the server and therefore can be ignored
// on the mobile application.
default:
android.util.Log.i(TAG, "Unknown state");
break;
}
// Failed login attempts, remaining = max - current
int currentFailCount = status.failCount;
int maxAllowedFailCount = status.maxFailCount;
int remainingFailCount = status.getRemainingAttempts();
if (status.getCustomObject() != null) {
// Custom object contains any proprietary server specific data
}
}
@Override
public void onActivationStatusFailed(Throwable t) {
// Network error occurred, report it to the user
}
});
} else {
// No activation present on device
}
```
Note that the status fetch may fail at an unrecoverable error `PowerAuthErrorCodes.PROTOCOL_UPGRADE`, meaning that it's not possible to upgrade the PowerAuth protocol to a newer version. In this case, it's recommended to [remove the activation locally](#activation-removal).
To get more information about activation lifecycle, check the [Activation States](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Activation.md#activation-states) chapter available in our [powerauth-crypto](https://github.com/wultra/powerauth-crypto) repository.
## Data Signing
The main feature of the PowerAuth protocol is data signing. PowerAuth has two types of signatures:
- **Symmetric Multi-Factor Signature**: Suitable for most operations, such as login, new payment or confirming changes in settings.
- **Asymmetric Private Key Signature**: Suitable for documents where a strong one-sided signature is desired.
- **Symmetric Offline Multi-Factor Signature**: Suitable for very secure operations, where the signature is validated over the out-of-band channel.
- **Verify server signed data**: Suitable for receiving arbitrary data from the server.
### Symmetric Multi-Factor Signature
To sign request data, you need to first obtain user credentials (password, PIN code, biometric image) from the user. The task of obtaining the user credentials is used in more use-cases covered by the SDK. The core class is `PowerAuthAuthentication` that holds information about the used authentication factors:
```java
// 2FA signature, uses device related key and user PIN code.
// To use biometry, you need to fetch the encrypted biometry key value using `BiometricPrompt.CryptoObject`.
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
```
When signing `POST`, `PUT` or `DELETE` requests, use request body bytes (UTF-8) as request data and the following code:
```java
// 2FA signature, uses device related key and user PIN code
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
// Sign POST call with provided data made to URI with custom identifier "/payment/create"
PowerAuthAuthorizationHttpHeader header = powerAuthSDK.requestSignatureWithAuthentication(context, authentication, "POST", "/payment/create", requestBodyBytes);
if (header.isValid()) {
String httpHeaderKey = header.getKey();
String httpHeaderValue = header.getValue();
} else {
// In case of invalid configuration, invalid activation state or corrupted state data
}
```
When signing `GET` requests, use the same code as above with normalized request data as described in specification, or (preferably) use the following helper method:
```java
// 2FA signature, uses device related key and user PIN code
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
// Sign GET call with provided query parameters made to URI with custom identifier "/payment/create"
Map<String, String> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
PowerAuthAuthorizationHttpHeader header = powerAuthSDK.requestGetSignatureWithAuthentication(context, authentication, "/payment/create", params);
if (header.isValid()) {
String httpHeaderKey = header.getKey();
String httpHeaderValue = header.getValue();
} else {
// In case of invalid configuration, invalid activation state or corrupted state data
}
```
The result of the signature is appropriate HTTP header - you are responsible for hooking up the header value in your request correctly. The process with libraries like `OkHttp` goes like this:
```java
// Prepare the request builder
final Request.Builder builder = new Request.Builder().url(endpoint);
// Compute PA signature header
PowerAuthAuthorizationHttpHeader header = powerAuthSDK.requestSignatureWithAuthentication(context, signatureUnlockKeys, "POST", "/session/login", jsonBody);
if (!header.isValid()) {
// request signature failed, for example due to incorrect activation status - cancel the process
return;
}
// Add HTTP header in the request builder
builder.header(header.getKey(), header.getValue());
// Build the request, send it and process response...
// ...
```
#### Request Synchronization
It is recommended that your application executes only one signed request at the time. The reason for that is that our signature scheme is using a counter as a representation of logical time. In other words, the order of request validation on the server is very important. If you issue more that one signed request at the same time, then the order is not guaranteed and therefore one from the requests may fail. On top of that, Mobile SDK itself is using this type of signatures for its own purposes. For example, if you ask for token, then the SDK is using signed request to obtain the token's data. To deal with this problem, Mobile SDK is providing a custom serial `Executor`, which can be used for signed requests execution:
```java
final Executor serialExecutor = powerAuthSDK.getSerialExecutor();
serialExecutor.execute(new Runnable() {
@Override
public void run() {
// Recommended practice:
// 1. You have to calculate PowerAuth signature here.
// 2. In case that you start yet another asynchronous operation from run(),
// then you have to wait for that operation's execution.
}
});
```
### Asymmetric Private Key Signature
Asymmetric Private Key Signature uses a private key stored in the PowerAuth secure vault. In order to unlock the secure vault and retrieve the private key, the user has to first authenticate using the symmetric multi-factor signature with at least two factors. This mechanism protects the private key on the device - the server plays a role of a "doorkeeper" and holds the vault unlock key.
This process is completely transparent on the SDK level. To compute an asymmetric private key signature, request user credentials (password, PIN, biometric image) and use the following code:
```java
// Prepare the authentication object
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
// Get the data to be signed
byte[] data = this.getMyData();
powerAuthSDK.signDataWithDevicePrivateKey(context, authentication, data, new IDataSignatureListener() {
@Override
public void onDataSignedSucceed(byte[] signature) {
// Use data signature...
}
@Override
public void onDataSignedFailed(Throwable t) {
// Report error
}
});
```
### Symmetric Offline Multi-Factor Signature
This type of signature is very similar to [Symmetric Multi-Factor Signature](#symmetric-multi-factor-signature) but the result is provided in the form of a simple, human-readable string (unlike the online version, where the result is HTTP header). To calculate the signature, you need a typical `PowerAuthAuthentication` object to define all required factors, nonce and data to sign. The `nonce` and `data` should also be transmitted to the application over the OOB channel (for example, by scanning a QR code). Then the signature calculation is straightforward:
```java
// Prepare the authentication object
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
final String signature = powerAuthSDK.offlineSignatureWithAuthentication(context, authentication, "/confirm/offline/operation", data, nonce);
if (signature != null) {
android.util.Log.d(TAG, "Offline signature is: " + signature);
} else {
// failure: session is probably invalid, or some required data is missing
}
```
The application has to show that calculated signature to the user now, and the user has to re-type that code into the web application for the verification.
### Verify Server-Signed Data
This task is useful whenever you need to receive arbitrary data from the server and you need to be able to verify that the server has issued the data. The PowerAuthSDK provides a high-level method for validating data and associated signature:
```java
// Validate data signed with the master server key
if (powerAuthSDK.verifyServerSignedData(data, signature, true)) {
// data is signed with server's private master key
}
// Validate data signed with the personalized server key
if (powerAuthSDK.verifyServerSignedData(data, signature, false)) {
// data is signed with server's private key
}
```
## Password Change
Since the device does not know the password and is unable to verify the password without the help of the server-side, you need to first call an endpoint that verifies a signature computed with the password. SDK offers two ways to do that.
The safe but typically slower way is to use the following code:
```java
// Change password from "<PASSWORD>" to "<PASSWORD>".
powerAuthSDK.changePassword(context, "oldPassword", "<PASSWORD>Password", new IChangePasswordListener() {
@Override
public void onPasswordChangeSucceed() {
// Password was changed
}
@Override
public void onPasswordChangeFailed(Throwable t) {
// Error occurred
}
})
```
This method calls `/pa/v3/signature/validate` under the hood with a 2FA signature with provided original password to verify the password correctness.
However, using this method does not usually fit the typical UI workflow of a password change. The method may be used in cases where an old password and a new password are on a single screen, and therefore are both available at the same time. In most mobile apps, however, the user first visits a screen to enter an old password, and then (if the password is OK), the user proceeds to the two-screen flow of a new password setup (select password, confirm password). In other words, the workflow works like this:
1. Show a screen to enter an old password.
2. Check an old password on the server.
3. If the old password is OK, then let the user chose and confirm a new one.
4. Change the password by re-encrypting the activation data.
For this purpose, you can use the following code:
```java
// Ask for an old password
String oldPassword = "<PASSWORD>";
// Validate password on the server
powerAuthSDK.validatePasswordCorrect(context, oldPassword, new IValidatePasswordListener() {
@Override
public void onPasswordValid() {
// Proceed to the new password setup
}
@Override
public void onPasswordValidationFailed(Throwable t) {
// Retry entering an old password
}
});
// ...
// Ask for new password
String newPassword = "<PASSWORD>";
// Change the password locally
powerAuthSDK.changePasswordUnsafe(oldPassword, newPassword);
```
<!-- begin box warning -->
**Now, beware!** Since the device does not know the actual old password, you need to make sure that the old password is validated before you use it in `unsafeChangePassword`. In case you provide the wrong old password, it will be used to decrypt the original data, and these data will be encrypted using a new password. As a result, the activation data will be broken and irreversibly lost.
<!-- end -->
## Biometric Authentication Setup
PowerAuth SDK for Android provides an abstraction on top of the base Biometric Authentication support. While the authentication / data signing itself is handled using the `PowerAuthAuthentication` object used in [regular request signing](#data-signing), other biometry-related processes require their own API.
### Check Biometric Authentication Status
You have to check for Biometric Authentication on three levels:
- **System Availability**: If biometric scanner is present on the system.
- **Activation Availability**: If biometry factor data are available for given activation.
- **Application Availability**: If user decided to use biometric authentication for given app. _(optional)_
PowerAuth SDK for Android provides code for the first and second of these checks.
To check if you can use the biometric authentication, use our helper class:
```java
// This method is equivalent to `BiometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS`.
// Use it to check if the biometric authentication can be used at the moment.
boolean isBiometricAuthAvailable = BiometricAuthentication.isBiometricAuthenticationAvailable(context);
// For more fine-grained control about the actual biometric authentication status,
// you may use the following code:
switch (BiometricAuthentication.canAuthenticate(context)) {
case BiometricStatus.OK:
// everything's OK
case BiometricStatus.NOT_SUPPORTED:
// device's hardware doesn't support biometry
case BiometricStatus.NOT_ENROLLED:
// there's no biometry data enrolled on the device
case BiometricStatus.NOT_AVAILABLE:
// The biometric authentication is not available at this time.
// You may try to retry the operation later.
}
// If you want to adjust localized strings or icons presented to the user,
// you can use the following code to determine the type of biometry available
// on the system:
switch (BiometricAuthentication.getBiometryType(context)) {
case BiometryType.NONE:
// Biometry is not supported on the system.
case BiometryType.GENERIC:
// It's not possible to determine exact type of biometry.
// This happens on Android 10+ systems, when the device supports
// more than one type of biometric authentication. In this case,
// you should use generic terms, like "Authenticate with biometry"
// for your UI.
case BiometryType.FINGERPRINT:
// Fingerprint scanner is present on the device.
case BiometryType.FACE:
// Face scanner is present on the device.
case BiometryType.IRIS:
// Iris scanner is present on the device.
}
```
To check if a given activation has biometry factor-related data available, use the following code:
```java
// Does activation have biometric factor-related data in place?
boolean hasBiometryFactor = powerAuthSDK.hasBiometryFactor(context);
```
The last check is fully under your control. By keeping the biometric settings flag, for example, a `BOOL` in `SharedPreferences`, you are able to show user an expected biometric authentication status (in a disabled state, though) even in the case biometric authentication is not enabled or when no fingers are enrolled on the device.
### Enable Biometric Authentication
In case an activation does not yet have biometry-related factor data, and you would like to enable biometric authentication support, the device must first retrieve the original private key from the secure vault for the purpose of key derivation. As a result, you have to use a successful 2FA with a password to enable biometric authentication support.
Use the following code to enable biometric authentication using biometric authentication:
```java
// Establish biometric data using provided password
powerAuthSDK.addBiometryFactor(context, fragment, "Enable Biometric Authentication", "To enable biometric authentication, use the biometric sensor on your device.", "1234", new IAddBiometryFactorListener() {
@Override
public void onAddBiometryFactorSucceed() {
// Everything went OK, biometric authentication is ready to be used
}
@Override
public void onAddBiometryFactorFailed(@NonNull PowerAuthErrorException error) {
// Error occurred, report it to user
}
});
```
By default, PowerAuth SDK asks user to authenticate with the biometric sensor also during the setup procedure (or during the [activation commit](#committing-activation-data)). To alter this behavior, use the following code to change `PowerAuthKeychainConfiguration` provided to `PowerAuthSDK` instance:
```java
PowerAuthKeychainConfiguration keychainConfig = new PowerAuthKeychainConfiguration.Builder()
.authenticateOnBiometricKeySetup(false)
.build();
// Apply keychain configuration
PowerAuthSDK powerAuthSDK = new PowerAuthSDK.Builder(configuration)
.keychainConfiguration(keychainConfig)
.build(getApplicationContext());
```
<!-- begin box info -->
Note that the RSA key-pair is internally generated for the configuration above. That may take more time on older devices than the default configuration. Your application should display a waiting indicator on its own, because SDK doesn't display an authentication dialog during the key-pair generation.
<!-- end -->
### Disable Biometric Authentication
You can remove biometry related factor data used by biometric authentication support by simply removing the related key locally, using this one-liner:
```java
// Remove biometric data
powerAuthSDK.removeBiometryFactor(context);
```
### Fetching the Biometry Factor-Related Key for Authentication
In order to obtain an encrypted biometry factor-related key for the purpose of authentication, call the following code:
```java
// Authenticate user with biometry and obtain encrypted biometry factor related key.
powerAuthSDK.authenticateUsingBiometry(context, fragment, "Sign in", "Use the biometric sensor on your device to continue", new IBiometricAuthenticationCallback() {
@Override
public void onBiometricDialogCancelled() {
// User cancelled the operation
}
@Override
public void onBiometricDialogSuccess(@NonNull BiometricKeyData biometricKeyData) {
// User authenticated and biometry key was returned
byte[] biometryFactorRelatedKey = biometricKeyData.getDerivedData();
}
@Override
public void onBiometricDialogFailed(@NonNull PowerAuthErrorException error) {
// Biometric authentication failed
}
});
```
### Biometry Factor-Related Key Lifetime
By default, the biometry factor-related key is invalidated after the biometry enrolled in the system is changed. For example, if the user adds or removes the finger or enrolls with a new face, then the biometry factor-related key is no longer available for the signing operation. To change this behavior, you have to provide `PowerAuthKeychainConfiguration` object with `linkBiometricItemsToCurrentSet` parameter set to `false` and use that configuration for the `PowerAuthSDK` instance construction:
```java
// Use false for 'linkBiometricItemsToCurrentSet' parameter.
PowerAuthKeychainConfiguration keychainConfig = new PowerAuthKeychainConfiguration.Builder()
.linkBiometricItemsToCurrentSet(false)
.build();
// Apply keychain configuration
PowerAuthSDK powerAuthSDK = new PowerAuthSDK.Builder(configuration)
.keychainConfiguration(keychainConfig)
.build(getApplicationContext());
```
Be aware that the configuration above is effective only for the new keys. So, if your application is already using the biometry factor-related key with a different configuration, then the configuration change doesn't change the existing key. You have to [disable](#disable-biometric-authentication) and [enable](#enable-biometric-authentication) biometry to apply the change.
### Biometric Authentication Details
The `BiometricAuthentication` class is a high level interface that provides interfaces related to the biometric authentication for the SDK, or for the application purposes. The class hides all technical details, so it can be safely used also on the systems that doesn't provide biometric interfaces, or if the system has no biometric sensor available. The implementation under the hood select the following two authentication methods, depending on the system version:
- Old, deprecated `FingerprintManager` class is used on Android 6 up to 8.1.
- In this case, SDK will display our custom dialog that instructs user to use its fingerprint scanner.
- New `BiometricPrompt` class is used on Android 9 and newer.
- In this case, a system provided prompt will be displayed.
- _Note that in this case, we still need to use a `FingerprintManager` to determine whether biometry is enrolled on the system. This is due to lack of such functionality in Android 9._
In case of [compatibility issues](https://github.com/wultra/powerauth-mobile-sdk/issues/251), you can force PowerAuth SDK to use the legacy `FingerprintManager` based authentication:
```java
BiometricAuthentication.setBiometricPromptAuthenticationDisabled(true);
```
To customize the strings used in biometric authentication, you can use `BiometricDialogResources` in the following manner:
```java
// Prepare new strings, colors, etc...
final BiometricDialogResources.Strings newStrings = new BiometricDialogResources.Strings(... constructor with string ids ...);
// Build new resources object.
// If you omit some custom resources object, then the Builder will replace that with resources bundled in SDK.
final BiometricDialogResources resources = new BiometricDialogResources.Builder(context)
.setStrings(newStrings)
.build();
// Set resources to BiometricAuthentication
BiometricAuthentication.setBiometricDialogResources(resources);
```
On Android 10+ systems, it's possible to configure `BiometricPrompt` to ask for an additional confirmation after the user is successfully authenticated. The default behavior for PowerAuth Mobile SDK is that such confirmation is not required. To change this behavior, you have to provide `PowerAuthKeychainConfiguration` object with `confirmBiometricAuthentication` parameter set to `true` and use that configuration for the `PowerAuthSDK` instance construction:
```java
// Use true for 'confirmBiometricAuthentication' parameter.
PowerAuthKeychainConfiguration keychainConfig = new PowerAuthKeychainConfiguration.Builder()
.confirmBiometricAuthentication(true)
.build();
// Apply keychain configuration
PowerAuthSDK powerAuthSDK = new PowerAuthSDK.Builder(configuration)
.keychainConfiguration(keychainConfig)
.build(getApplicationContext());
```
## Activation Removal
You can remove activation using several ways - the choice depends on the desired behavior.
### Simple Device-Only Removal
You can clear activation data anytime from the `SharedPreferences`. The benefit of this method is that it does not require help from the server, and the user does not have to be logged in. The issue with this removal method is simple: The activation still remains active on the server-side. This, however, does not have to be an issue in your case.
To remove only data related to PowerAuth SDK for Android, use the following code:
```java
powerAuthSDK.removeActivationLocal(context);
```
### Removal via Authenticated Session
Suppose your server uses an authenticated session for keeping the users logged in. In that case, you can combine the previous method with calling your proprietary endpoint to remove activation for the currently logged-in user. The advantage of this method is that activation does not remain active on the server. The issue is that the user has to be logged in (the session must be active and must have activation ID stored) and that you have to publish your own method to handle this use case.
The code for this activation removal method is as follows:
```java
// Use custom call to proprietary server endpoint to remove activation.
// User must be logged in at this moment, so that session can find
// associated activation ID
this.httpClient.post(null, "/custom/activation/remove", new ICustomListener() {
@Override
public void onSucceed() {
powerAuthSDK.removeActivationLocal(context);
}
@Override
public void onFailed(Throwable t) {
// Error occurred, report it to user
}
});
```
### Removal via Signed Request
PowerAuth Standard RESTful API has a default endpoint `/pa/v3/activation/remove` for an activation removal. This endpoint uses a signature verification for looking up the activation to be removed. The benefit of this method is that it is already present in both PowerAuth SDK for Android and PowerAuth Standard RESTful API - nothing has to be programmed. Also, the user does not have to be logged in to use it. However, the user has to authenticate using 2FA with either password or biometric authentication.
Use the following code for an activation removal using signed request:
```java
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
// Remove activation using provided authentication object
powerAuthSDK.removeActivationWithAuthentication(context, authentication, new IActivationRemoveListener() {
@Override
public void onActivationRemoveSucceed() {
// OK, activation was removed
}
@Override
public void onActivationRemoveFailed(Throwable t) {
// Report error to user
}
})
```
## End-To-End Encryption
Currently, PowerAuth SDK supports two basic modes of end-to-end encryption, based on the ECIES scheme:
- In an "application" scope, the encryptor can be acquired and used during the whole lifetime of the application.
- In an "activation" scope, the encryptor can be acquired only if `PowerAuthSDK` has a valid activation. The encryptor created for this mode is cryptographically bound to the parameters agreed during the activation process. You can combine this encryption with [PowerAuth Symmetric Multi-Factor Signature](#symmetric-multi-factor-signature) in "sign-then-encrypt" mode.
For both scenarios, you need to acquire `EciesEncryptor` object, which will then provide interface for the request encryption and the response decryption. The object currently provides only low level encryption and decryption methods, so you need to implement your own JSON (de)serialization and request and response processing.
The following steps are typically required for a full E2EE request and response processing:
1. Acquire the right encryptor from the `PowerAuthSDK` instance. For example:
```java
// Encryptor for "application" scope.
final EciesEncryptor encryptor = powerAuthSDK.getEciesEncryptorForApplicationScope();
// ...or similar, for an "activation" scope.
final EciesEncryptor encryptor = powerAuthSDK.getEciesEncryptorForActivationScope(context);
```
2. Serialize your request payload, if needed, into a sequence of bytes. This step typically means that you need to serialize your model object into a JSON formatted sequence of bytes.
3. Encrypt your payload:
```java
final EciesCryptogram cryptogram = encryptor.encryptRequest(payloadData);
if (cryptogram == null) {
// cannot encrypt data
}
```
4. Construct a JSON from provided cryptogram object. The dictionary with the following keys is expected:
- `ephemeralPublicKey` property fill with `cryptogram.getKeyBase64()`
- `encryptedData` property fill with `cryptogram.getBodyBase64()`
- `mac` property fill with `cryptogram.getMacBase64()`
- `nonce` property fill with `cryptogram.getNonceBase64()`
So, the final request JSON should look like this:
```json
{
"ephemeralPublicKey" : "BASE64-DATA-BLOB",
"encryptedData": "BASE64-DATA-BLOB",
"mac" : "BASE64-DATA-BLOB",
"nonce" : "BASE64-NONCE"
}
```
5. Add the following HTTP header (for signed requests, see note below):
```java
// Acquire a "metadata" object, which contains additional information for the request construction
final EciesMetadata metadata = encryptor.getMetadata();
final String httpHeaderName = metadata.getHttpHeaderKey();
final String httpHeaderValue = metadata.getHttpHeaderValue();
```
Note, that if an "activation" scoped encryptor is combined with PowerAuth Symmetric Multi-Factor signature, then this step is not required. The signature's header already contains all information required for proper request decryption on the server.
6. Fire your HTTP request and wait for a response
- In case that non-200 HTTP status code is received, then the error processing is identical to a standard RESTful response defined in our protocol. So, you can expect a JSON object with `"error"` and `"message"` properties in the response.
7. Decrypt the response. The received JSON typically looks like this:
```json
{
"encryptedData": "BASE64-DATA-BLOB",
"mac" : "BASE64-DATA-BLOB"
}
```
So, you need to create yet another "cryptogram" object, but with only two properties set:
```java
final EciesCryptogram responseCryptogram = new EciesCryptogram(response.getEncryptedData(), response.getMac());
final byte[] responseData = encryptor.decryptResponse(responseCryptogram);
if (responseData == null) {
// failed to decrypt response data
}
```
8. And finally, you can process your received response.
As you can see, the E2EE is quite a non-trivial task. We recommend contacting us before using an application-specific E2EE. We can provide you more support on a per-scenario basis, especially if we first understand what you try to achieve with end-to-end encryption in your application.
## Secure Vault
PowerAuth SDK for Android has basic support for an encrypted secure vault. At this moment, the only supported method allows your application to establish an encryption / decryption key with a given index. The index represents a "key number" - your identifier for a given key. Different business logic purposes should have encryption keys with a different index value.
On a server side, all secure vault related work is concentrated in a `/pa/v3/vault/unlock` endpoint of PowerAuth Standard RESTful API. In order to receive data from this response, call must be authenticated with at least 2FA (using password or PIN).
<!-- begin box warning -->
Secure vault mechanism does not support biometry by default. Use PIN code or password based authentication for unlocking the secure vault, or ask your server developers to enable biometry for vault unlock call by configuring PowerAuth Server instance.
<!-- end -->
### Obtaining Encryption Key
In order to obtain an encryption key with a given index, use the following code:
```java
// 2FA signature. It uses device related key and user PIN code.
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
// Select custom key index
long index = 1000L;
// Fetch encryption key with given index
powerAuthSDK.fetchEncryptionKey(context, authentication, index, new IFetchEncryptionKeyListener() {
@Override
public void onFetchEncryptionKeySucceed(byte[] encryptedEncryptionKey) {
// ... use encryption key to encrypt or decrypt data
}
@Override
public void onFetchEncryptionKeyFailed(Throwable t) {
// Report error
}
})
```
## Recovery Codes
The recovery codes allow your users to recover their activation in case that mobile device is lost or stolen. Before you start, please read the [Activation Recovery](https://github.com/wultra/powerauth-crypto/blob/develop/docs/Activation-Recovery.md) document, available in our [powerauth-crypto](https://github.com/wultra/powerauth-crypto) repository.
To recover an activation, the user has to re-type two separate values:
1. Recovery Code itself, which is very similar to an activation code. So you can detect typing errors before you submit such code to the server.
1. PUK, which is an additional numeric value and acts as a one-time password in the scheme.
PowerAuth currently supports two basic types of recovery codes:
1. Recovery Code bound to a previous PowerAuth activation.
- This type of code can be obtained only in an already activated application.
- This type of code has only one PUK available, so only one recovery operation is possible.
- The activation associated with the code is removed once the recovery operation succeeds.
2. Recovery Code delivered via OOB channel, typically in the form of a securely printed postcard, delivered by the post service.
- This type of code has typically more than one PUK associated with the code, so it can be used multiple times.
- The user has to keep that postcard in safe and secure place, and mark already used PUKs.
- The code delivery must be confirmed by the user before the code can be used for a recovery operation.
The feature is not automatically available. It must be enabled and configured on PowerAuth Server. If it's so, then your mobile application can use several methods related to this feature.
### Getting Recovery Data
If the recovery data was received during the activation process, then you can later display that information to the user. To check existence of recovery data and get that information, use the following code:
```java
if (!powerAuthSDK.hasActivationRecoveryData()) {
// Recovery information is not available
return;
}
// 2FA signature, uses device related key and user PIN code
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
powerAuthSDK.getActivationRecoveryData(context, authentication, new IGetRecoveryDataListener() {
@Override
public void onGetRecoveryDataSucceeded(RecoveryData recoveryData) {
final String recoveryCode = recoveryData.recoveryCode;
final String puk = recoveryData.puk;
// Show values on the screen...
}
@Override
public void onGetRecoveryDataFailed(Throwable t) {
// Report error
}
});
```
The obtained information is very sensitive, so you should be very careful how your application manipulates the received values:
- You should never store `recoveryCode` or `puk` on the device.
- You should never print the values to the debug log.
- You should never send the values over the network.
- You should never copy the values to the clipboard.
- You should require PIN code every time to display the values on the screen.
- You should warn user that taking screenshot of the values is not recommended.
- Do not cache the values in RAM.
You should inform the user that:
- Making a screenshot when values are displayed on the screen is dangerous.
- The user should write down that values on paper and keep it as much safe as possible for future use.
### Confirm Recovery Postcard
The recovery postcard can contain the recovery code and multiple PUK values on one printed card. Due to security reasons, this kind of recovery code cannot be used for the recovery operation before the user confirms its physical delivery. To confirm such recovery code, use the following code:
```java
// 2FA signature with possession factor is required
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
authentication.usePassword = "<PASSWORD>";
authentication.useBiometry = null;
final String recoveryCode = "VVVVV-VVVVV-VVVVV-VTFVA" // You can also use code scanned from QR
powerAuthSDK.confirmRecoveryCode(context, authentication, recoveryCode, new IConfirmRecoveryCodeListener{
@Override
public void onRecoveryCodeConfirmed(boolean alreadyConfirmed) {
if (alreadyConfirmed) {
android.util.Log.d(TAG, "Recovery code has been already confirmed. This is not an error, just information.");
} else {
android.util.Log.d(TAG, "Recovery code has been successfully confirmed.");
}
}
@Override
public void onRecoveryCodeConfirmFailed(Throwable t) {
// Report error
}
});
```
The `alreadyConfirmed` boolean indicates that the code was already confirmed in the past. You can choose a different "success" screen, describing that the user has already confirmed such code. Also, note that codes bound to the activations are already confirmed.
## Token-Based Authentication
<!-- begin box warning -->
**WARNING:** Before you start using access tokens, please visit our [wiki page for powerauth-crypto](https://github.com/wultra/powerauth-crypto/blob/develop/docs/MAC-Token-Based-Authentication.md) for more information about this feature.
<!-- end -->
The tokens are simple, locally cached objects, producing timestamp-based authorization headers. Be aware that tokens are NOT a replacement for general PowerAuth signatures. They are helpful in situations when the signatures are too heavy or too complicated for implementation. Each token has the following properties:
- It needs PowerAuth signature for its creation (e.g., you need to provide `PowerAuthAuthentication` object)
- It has a unique identifier on the server. This identifier is not exposed to the public API, but you can reveal that value in the debugger.
- It has symbolic name (e.g., "MyToken") defined by the application programmer to identify already created tokens.
- It can generate timestamp-based authorization HTTP headers.
- It can be used concurrently. Token's private data doesn't change in time.
- The token is associated with the `PowerAuthSDK` instance. So, you can use the same symbolic name in multiple SDK instances, and each created token will be unique.
- Tokens are persisted in the `KeychainFactory` service and cached in the memory.
- Once the parent `PowerAuthSDK` instance loses its activation, all its tokens are removed from the local database.
### Getting Token
To get an access token, you can use the following code:
```java
// 1FA signature, uses device related key
PowerAuthAuthentication authentication = new PowerAuthAuthentication();
authentication.usePossession = true;
final PowerAuthTokenStore tokenStore = powerAuthSDK.getTokenStore();
final AsyncTask task = tokenStore.requestAccessToken(context, "MyToken", authentication, new IGetTokenListener() {
@Override
public void onGetTokenSucceeded(@NonNull PowerAuthToken powerAuthToken) {
// the token has been successfully acquired
}
@Override
public void onGetTokenFailed(@NonNull Throwable throwable) {
// an error occurred
}
});
```
The request is performed synchronously or asynchronously depending on whether the token is locally cached on the device. You can test this situation by calling `tokenStore.hasLocalToken(context, "MyToken")`. If operation is asynchronous, then `requestAccessToken()` returns cancellable task. Be aware that you should not issue multiple asynchronous operations for the same token name.
### Generating Authorization Header
Once you have a `PowerAuthToken` object, use the following code to generate an authorization header:
```java
PowerAuthAuthorizationHttpHeader header = token.generateHeader();
if (header.isValid()) {
// Header is valid, you can construct HTTP header...
String httpHeaderKey = header.key;
String httpHeaderValue = header.value;
} else {
// handle error
}
```
### Removing Token From the Server
To remove the token from the server, you can use the following code:
```java
final PowerAuthTokenStore tokenStore = powerAuthSDK.getTokenStore();
tokenStore.removeAccessToken(context, "MyToken", new IRemoveTokenListener() {
@Override
public void onRemoveTokenSucceeded() {
android.util.Log.d(TAG, "Token has been removed");
}
@Override
public void onRemoveTokenFailed(@NonNull Throwable t) {
// handle HTTP error
}
});
```
### Removing Token Locally
To remove token locally, you can simply use the following code:
```java
final PowerAuthTokenStore tokenStore = powerAuthSDK.getTokenStore();
// Remove just one token
tokenStore.removeLocalToken(context, "MyToken");
// Remove all local tokens
tokenStore.removeAllLocalTokens(context);
```
Note that by removing tokens locally, you will lose control of the tokens stored on the server.
## Common SDK Tasks
### Error Handling
The PowerAuth SDK is using the following types of exceptions:
- `PowerAuthMissingConfigException` - is typically thrown immediately when `PowerAuthSDK` instance is initialized with an invalid configuration.
- `FailedApiException` - is typically returned to callbacks when an asynchronous HTTP request ends on error.
- `ErrorResponseApiException` - is typically returned to callbacks when an asynchronous HTTP request ends on error and the error model object is present in the response.
- `PowerAuthErrorException` - typically covers all other erroneous situations. You can investigate a detailed reason of failure by getting the integer, from set of `PowerAuthErrorCodes` constants.
Here's an example for a typical error handling procedure:
```java
Throwable t; // reported in asynchronous callback
if (t instanceof PowerAuthErrorException) {
switch (((PowerAuthErrorException) t).getPowerAuthErrorCode()) {
case PowerAuthErrorCodes.NETWORK_ERROR:
android.util.Log.d(TAG, "Error code for error with network connectivity or download"); break;
case PowerAuthErrorCodes.SIGNATURE_ERROR:
android.util.Log.d(TAG,"Error code for error in signature calculation"); break;
case PowerAuthErrorCodes.INVALID_ACTIVATION_STATE:
android.util.Log.d(TAG,"Error code for error that occurs when activation state is invalid"); break;
case PowerAuthErrorCodes.INVALID_ACTIVATION_DATA:
android.util.Log.d(TAG,"Error code for error that occurs when activation data is invalid"); break;
case PowerAuthErrorCodes.MISSING_ACTIVATION:
android.util.Log.d(TAG,"Error code for error that occurs when activation is required but missing"); break;
case PowerAuthErrorCodes.PENDING_ACTIVATION:
android.util.Log.d(TAG,"Error code for error that occurs when pending activation is present and work with completed activation is required"); break;
case PowerAuthErrorCodes.INVALID_ACTIVATION_CODE:
android.util.Log.d(TAG,"Error code for error that occurs when invalid activation code is provided."); break;
case PowerAuthErrorCodes.BIOMETRY_CANCEL:
android.util.Log.d(TAG,"Error code for Biometry action cancel error"); break;
case PowerAuthErrorCodes.BIOMETRY_NOT_SUPPORTED:
android.util.Log.d(TAG,"The device or operating system doesn't support biometric authentication."); break;
case PowerAuthErrorCodes.BIOMETRY_NOT_AVAILABLE:
android.util.Log.d(TAG,"The biometric authentication is temporarily unavailable."); break;
case PowerAuthErrorCodes.BIOMETRY_NOT_RECOGNIZED:
android.util.Log.d(TAG,"The biometric authentication did not recognize the biometric image (fingerprint, face, etc...)"); break;
case PowerAuthErrorCodes.BIOMETRY_LOCKOUT:
android.util.Log.d(TAG,"The biometric authentication is locked out due to too many failed attempts."); break;
case PowerAuthErrorCodes.OPERATION_CANCELED:
android.util.Log.d(TAG,"Error code for cancelled operations"); break;
case PowerAuthErrorCodes.ENCRYPTION_ERROR:
android.util.Log.d(TAG,"Error code for errors related to end-to-end encryption"); break;
case PowerAuthErrorCodes.INVALID_TOKEN:
android.util.Log.d(TAG,"Error code for errors related to token based auth."); break;
case PowerAuthErrorCodes.PROTOCOL_UPGRADE:
android.util.Log.d(TAG,"Error code for error that occurs when protocol upgrade fails at unrecoverable error."); break;
case PowerAuthErrorCodes.PENDING_PROTOCOL_UPGRADE:
android.util.Log.d(TAG,"The operation is temporarily unavailable, due to pending protocol upgrade."); break;
}
} else if (t instanceof ErrorResponseApiException) {
ErrorResponseApiException exception = (ErrorResponseApiException) t;
Error errorResponse = exception.getErrorResponse();
int httpResponseStatusCode = exception.getResponseCode();
// Additional, optional objects assigned to the exception.
JsonObject jsonResponseObject = exception.getResponseJson();
String responseBodyString = exception.getResponseBody();
} else if (t instanceof FailedApiException) {
FailedApiException exception = (FailedApiException) t;
int httpStatusCode = exception.getResponseCode();
// Additional, optional objects assigned to the exception.
JsonObject jsonResponseObject = exception.getResponseJson();
String responseBodyString = exception.getResponseBody();
}
```
Note that you typically don't need to handle all error codes reported in the `PowerAuthErrorException`, or report all that situations to the user. Most of the codes are informational and help the developers properly integrate SDK into the application. A good example is `INVALID_ACTIVATION_STATE`, which typically means that your application's logic is broken and you're using PowerAuthSDK in an unexpected way.
Here's the list of important error codes, which the application should properly handle:
- `BIOMETRY_CANCEL` is reported when the user cancels the biometric authentication dialog
- `PROTOCOL_UPGRADE` is reported when SDK failed to upgrade itself to a newer protocol version. The code may be reported from `PowerAuthSDK.fetchActivationStatusWithCallback()`. This is an unrecoverable error resulting in the broken activation on the device, so the best situation is to inform user about the situation and remove the activation locally.
- `PENDING_PROTOCOL_UPGRADE` is reported when the requested SDK operation cannot be completed due to a pending PowerAuth protocol upgrade. You can retry the operation later. The code is typically reported in the situations when SDK is performing protocol upgrade on the background (as a part of activation status fetch), and the application want's to calculate PowerAuth signature in parallel operation. Such kind of concurrency is forbidden since SDK version `1.0.0`
### Working with Invalid SSL Certificates
Sometimes, you may need to develop or test your application against a service that runs over HTTPS protocol with an invalid (self-signed) SSL certificate. By default, the HTTP client used in PowerAuth SDK communication validates the certificate. To disable the certificate validation, use a `PowerAuthSDK` initializer with a custom client configuration to initialize your PowerAuth SDK instance, like so:
```java
// Set `HttpClientSslNoValidationStrategy as the defauld client SSL certificate validation strategy`
final PowerAuthClientConfiguration clientConfiguration = new PowerAuthClientConfiguration.Builder()
.clientValidationStrategy(new HttpClientSslNoValidationStrategy())
.build();
// Prepare the configuration, see above...
// ...
// Create a PowerAuth SDK instance
PowerAuthSDK powerAuthSDK = new PowerAuthSDK();
powerAuthSDK.initializeWithConfiguration(context, configuration, clientConfiguration);
```
Be aware, that using this option will lead to use an unsafe implementation of `HostnameVerifier` and `X509TrustManager` SSL client validation. This is useful for debug/testing purposes only, e.g. when untrusted self-signed SSL certificate is used on server side.
It's strictly recommended to use this option only in debug flavours of your application. Deploying to production may cause "Security alert" in Google Developer Console. Please see [this](https://support.google.com/faqs/answer/7188426) and [this](https://support.google.com/faqs/answer/6346016) Google Help Center articles for more details. Beginning 1 March 2017, Google Play will block publishing of any new apps or updates that use such unsafe implementation of `HostnameVerifier`.
How to solve this problem for debug/production flavours in the Gradle build script:
1. Define boolean type `buildConfigField` in the flavour configuration.
```gradle
productFlavors {
production {
buildConfigField 'boolean', 'TRUST_ALL_SSL_HOSTS', 'false'
}
debug {
buildConfigField 'boolean', 'TRUST_ALL_SSL_HOSTS', 'true'
}
}
```
2. In code use this conditional initialization for `PowerAuthClientConfiguration.Builder` builder.
```java
PowerAuthClientConfiguration.Builder clientBuilder = new PowerAuthClientConfiguration.Builder();
if (BuildConfig.TRUST_ALL_SSL_HOSTS) {
clientBuilder.clientValidationStrategy(new HttpClientSslNoValidationStrategy());
}
```
3. Set `minifyEnabled` to true for release buildType to enable code shrinking with ProGuard.
### Debugging
The debug log is by default turned off. To turn it on, use the following code:
```java
PowerAuthLog.setEnabled(true);
```
To turn-on even more detailed log, use the following code:
```java
PowerAuthLog.setVerbose(true);
```
Note that it's highly recommended to turn-on this feature only for `DEBUG` build of your application. For example:
```java
if (BuildConfig.DEBUG) {
PowerAuthLog.setEnabled(true);
}
```
## Additional Features
PowerAuth SDK for Android contains multiple additional features that are useful for mobile apps.
### Password Strength Indicator
Choosing a weak passphrase in applications with high-security demands can be potentially dangerous. You can use our [Wultra Passphrase Meter](https://github.com/wultra/passphrase-meter) library to estimate the strength of the passphrase and warn the user when he tries to use such a passphrase in your application.
### Debug Build Detection
It is sometimes useful to switch PowerAuth SDK to a DEBUG build configuration to get more logs from the library. The DEBUG build is usually helpful during the application development, but on the other hand, it's highly unwanted in production applications. For this purpose, the `PowerAuthSDK.hasDebugFeatures()` method provides information whether the PowerAuth JNI library was compiled in DEBUG configuration. It is a good practice to check this flag and crash the process when the production application is linked against the DEBUG PowerAuth:
```java
if (!BuildConfig.DEBUG) {
// You can also check your production build configuration
if (powerAuthSDK.hasDebugFeatures()) {
throw new RuntimeException("Production app with DEBUG PowerAuth");
}
}
```
### Request Interceptors
The `PowerAuthClientConfiguration` can contain multiple request interceptor objects, allowing you to adjust all HTTP requests created by SDK, before execution. Currently, you can use the following two classes:
- `BasicHttpAuthenticationRequestInterceptor` to add basic HTTP authentication header to all requests
- `CustomHeaderRequestInterceptor` to add a custom HTTP header to all requests
For example:
```java
final PowerAuthClientConfiguration clientConfiguration = new PowerAuthClientConfiguration.Builder()
.requestInterceptor(new BasicHttpAuthenticationRequestInterceptor("gateway-user", "gateway-password"))
.requestInterceptor(new CustomHeaderRequestInterceptor("X-CustomHeader", "123456"))
.build();
```
We don't recommend implementing the `HttpRequestInterceptor` interface on your own. The interface allows you to tweak the requests created in the `PowerAuthSDK` but also gives you an opportunity to break things. So, rather than create your own interceptor, try to contact us and describe what's your problem with the networking in the PowerAuth SDK. Also, keep in mind that the interface may change in the future. We can guarantee the API stability of public classes implementing this interface, but not the stability of the interface itself.
| docs/PowerAuth-SDK-for-Android.md | [
"VisIt"
] | 6fcc52a0122fcd32e3b997b9176cc3b86441592f52bde6ccc696fa17b49d94d8 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 216