%\VignetteIndexEntry{BaseSpaceR}
%\VignetteDepends{BaseSpaceR}
%\VignetteKeywords{BaseSpace}
%\VignettePackage{BaseSpaceR}

\documentclass[a4paper, oneside, 10pt]{article}

%%\usepackage[pdftex]{hyperref}
\usepackage{hyperref}
\usepackage{calc}
\usepackage{sectsty}
\usepackage{caption}
\usepackage{natbib}
\renewcommand{\captionfont}{\it\sffamily}
\renewcommand{\captionlabelfont}{\bf\sffamily}
\allsectionsfont{\sffamily}

% page style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[a4paper, left=25mm, right=20mm, top=20mm, bottom=25mm, nohead]{geometry}
\setlength{\parskip}{1.5ex}
\setlength{\parindent}{0cm}
\pagestyle{empty}


\usepackage{Sweave}
\SweaveOpts{prefix.string = BaseSpaceR}


\title{\vspace*{-6ex} BaseSpaceR}
\author{Adrian Alexa}
\date{\today \\%
  \texttt{aalexa@illumina.com}}

\begin{document}
\maketitle

%%\newpage
\tableofcontents
\newpage

<<echo = FALSE>>=
options(width = 95)
@ 

\section{Introduction}
\label{sec:intro}
The {\tt BaseSpaceR} package provides a complete R interface to Illumina's
\href{https://developer.basespace.illumina.com/docs/content/documentation/rest-api/api-reference}{BaseSpace REST API},
enabling the fast development of data analysis and visualisation tools. 
Besides providing an easy to use set of tools for manipulating the data from BaseSpace,
it also facilitates the access to R's rich environment of statistical and data analysis
open source tools.

Features include:
\begin{itemize}
\item Persistent connection with the REST server.
\item Support for the REST API query parameters.
\item Vectorized operations in line with the R semantic. Allows for queries across
  multiple Projects, Samples, AppResults, Files, etc.
\item S4 class system used to represent the BaseSpace data model.
\item Templates for uploading and creating AppResults {\it [under development]}.
\item Integration with Bioconductor libraries and data containers {\it [under development]}.
\item Portability on most platforms: Linux, Windows and Mac OS X.
\end{itemize}

BaseSpace is a proprietary cloud platform developed by 
\href{http://www.illumina.com/}{Illumina} for storing, analyzing and sharing genetic data.
General information about BaseSpace can be found at \href{https://basespace.illumina.com}{basespace.illumina.com}
and resources for BaseSpace developers can be found at
\href{https://developer.basespace.illumina.com}{developer.basespace.illumina.com}.


\subsection{Developing BaseSpace applications}
\label{subsec:appdevel}

The following briefly presents the steps necessary to get started with {\tt BaseSpaceR}
and the process of creating a new App. At the same time it provides an outlook of
the sections to follow. It is essential for the developer to read through BaseSpace's 
\href{https://developer.basespace.illumina.com/docs/content/documentation/getting-started/overview}{Getting Started}
guide to better understand these steps.

\begin{enumerate}
\item Register as BaseSpace developer. You can do this at 
  \href{https://developer.basespace.illumina.com/dashboard}{developer.basespace.illumina.com/dashboard}.
    
\item Understand the types of applications you can develop using BaseSpace and the 
  underlying \href{https://developer.basespace.illumina.com/docs/content/documentation/rest-api/data-model-overview}{API data model}.
  Section~\ref{sec:dataModel} gives an overview of the data model exposed by the BaseSpace
  API and the way is implemented in {\tt BaseSpaceR}.
  
\item Register your new application using \href{https://developer.basespace.illumina.com/apps}{BaseSpace's application management}.
  You will need the {\tt client\_id} and the {\tt client\_secret} to enable communication
  between your App and BaseSpace.

\item Learn the \href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/authenticating}{Authentication}
  process and \href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/using-scope}{BaseSpace Permissions}.
  Section~\ref{sec:auth} shows how manage these processes from within R.
  
\item Think about what data your application will need and which BaseSpace resources you'll
  have to query. Section~\ref{sec:quickGuide} gives an overview on how to manipulate some
  of these resources.
  
\item Refer to the 
  \href{https://developer.basespace.illumina.com/release-notes/content/release-notes/apichangelog}{Release Notes}
  to keep up on changes to the REST API and 
  \href{https://groups.google.com/forum/?fromgroups=#!forum/basespace-developers}{BaseSpace Developer Group}
  to ask questions or provide feedback.
\end{enumerate}


We further assume the user has some familiarity with the 
\href{https://developer.basespace.illumina.com/docs}{BaseSpace API} and the 
\href{http://www.r-project.org}{R environment}.
Most of the exposed R methods take the same parameters as the REST methods they
implement/use and we advise the developers to regularly check the
\href{https://developer.basespace.illumina.com/docs/content/documentation/rest-api/api-reference}{REST API reference}
documentation.  


\section{Installation}
\label{sec:install}

This section briefly describes the necessary steps to get {\tt BaseSpaceR} running on
your system. We assume the user have the \href{http://www.r-project.org}{R environment}
already installed and it is fairly familiar with it. R 2.15.0 or later and {\tt RCurl}
and {\tt RJSONIO} packages are required for installing and running {\tt BaseSpaceR}.
 
The {\tt BaseSpaceR} package is available from the \href{http://www.bioconductor.org}{Bioconductor} repository.
In order to install the package one needs first to install the core Bioconductor packages. 
If you have already installed Bioconductor packages on your system then you can skip
the two lines below.

<<eval = FALSE>>=
source("http://bioconductor.org/biocLite.R")
biocLite()
@ 

Once the core Bioconductor packages are installed, we can install the 
{\tt BaseSpaceR} package by:

<<eval = FALSE>>=
source("http://bioconductor.org/biocLite.R")
biocLite("BaseSpaceR")
@ 

To use the package we load it using the {\tt library()} function.
<<>>=
library(BaseSpaceR)
@

Note that when the {\tt BaseSpaceR} package is loaded, both {\tt RCurl} and {\tt RJSONIO}
packages are automatically loaded.



\section{BaseSpace data model}
\label{sec:dataModel}


The data model exposed by the BaseSpace API consists of the following major
{\bf resources/entities}:

\begin{itemize}
\item[] {\bf Users:} A user is the individual performing the analysis in BaseSpace.
\item[] {\bf Runs:} A run is a collection of BCL files associated with an individual
  flow cell and contains metrics and reads generated by the instrument on which the
  flow cell was sequenced.
\item[] {\bf Projects:} A project is a logical grouping of Samples and AppResults for a user.
\item[] {\bf Samples:} A sample is a collection of FASTQ files of Reads. Sample
  contains metadata about the physical subject. Samples files are generally 
  used as inputs to Apps.
\item[] {\bf AppResults:} An AppResult is an output of an App. It contains BAMs, VCFs 
  and other output file formats produced by an App.
\item[] {\bf AppSessions:} AppSession extends information about each Sample and
  AppResult and allows grouping by showing the instance of an application.
\item[] {\bf Files:} The files associated with a Run, Sample, or AppResult. All files
  for each resource are in the File resource.
\item[] {\bf Genomes:} These are the reference genome sequences that exist in BaseSpace.
  This resource gives information about the origin and build for each genome
\end{itemize}

{\tt BaseSpaceR} provides classes and methods to interface with this data model.
Each {\bf resource} is modeled by a S4 class. For every query the REST server receives,
a response in the form of a JSON object is return.

Conceptually there are two response types exposed by BaseSpace, an individual response 
and a collection response. The former, modeled by the R  {\tt Item} class, is used when 
querying an individual item/instance (specified by the item ID) within a resource.
The later is used for listing the items/instances available for a given resource and is
modeled by the R {\tt Collection} class.

\subsection{{\tt Item} objects}
\label{subsec:item}

The {\tt Item} class models a simple unordered set of key/value pairs. There is a core 
set of keys, for which access methods are defined and which are inherited by any
child class. These methods are: {\tt Id()}, {\tt Name()}, {\tt Href()},
{\tt DateCreated()}, {\tt UserOwnedBy()}, {\tt Status()}, and {\tt HrefBaseSpaceUI()}.

The class also implements a generic user level access operator, the {\tt \$} operator.
It behavior of this operator is similar to its behavior on the {\tt list} object. 
Thus, if the specified name is not a key of the instance, then NULL is returned. 
We can use this operator to access the core keys and we the following 
{\tt Id(x) == x\$Id} stands for all core keys. 

\subsection{{\tt Collection} objects}
\label{subsec:collection}

The {\tt Collection} class models an ordered set of {\tt Item} objects and a set of
predefined attributes. The interface provided by the {\tt Item} class is implemented by 
this class. However, since we deal with an ordered set of objects, the methods and the 
access methods, return a vector of the same length as the size of the collection.

{\tt Collection} class implements the following methods for accessing the set 
attributes: {\tt Items()}, {\tt DisplayedCount()}, {\tt TotalCount()}, 
{\tt Offset()}, {\tt Limit()}, {\tt SortDir}, and {\tt SortBy()}.

This is in line with the way the \href{https://developer.basespace.illumina.com/docs/content/documentation/rest-api/api-reference#Individual_Resource_Requests}{REST API}
defines the response objects.


\subsection{{\tt Response} objects}
\label{subsec:response}

Response objects consists of either an {\tt Item} or a {\tt Collection} object and 
an {\tt AppAuth} object (the handler used to communicate with the server, see 
Section~\ref{sec:auth}).

Every class representing a BaseSpace resource implements the {\tt Response} interface. 
For example, for the Projects resource we have two classes {\tt Projects} and
{\tt ProjectsSummary}. The former implements the {\tt Item} interface, while the latter
implements the {\tt Collection} interface. Queries to the Projects resource return an
instance one of these two objects 



\section{Sample Session - Quick API guide}
\label{sec:quickGuide}

This section describes a few of the API calls implemented by this SDK, that should be
sufficient to give the user a flavor of how it works. Please note that within this 
document we are limited by the permission to the BaseSpace resources. Therefore the
examples shown here are restricted to browsing the data. 

A more comprehensive example, in which we select the FASTQ file(s) from a sample and
compute Q-score statistics, can be seen in the other vignette shipped with this package,
{\tt BaseSpaceR-QscoreApp.pdf}.

A typical BaseSpace session can be divided into the following steps:
\begin{itemize}
\item Client authentication
\item Data retrieval and access
\item Data processing
\item Uploading results back to BaseSpace
\end{itemize}

Bellow we'll focus on the first two steps and we'll briefly describe the others.


\paragraph{Authentication}
The first step is the authentication of the client application with BaseSpace. There
are several ways in which this process can be triggered. Section~\ref{sec:auth} details
the authentication process and the available options.

The communication between the client and the server is handled by an {\tt AppAuth}
instance. {\tt BaseSpaceR} comes with an {\tt AppAuth} instance offering restricted 
access to BaseSpace resources. For simplicity, we'll use this instance here.

<<>>=
data(aAuth)
aAuth
@ 

If the access token is valid, which it is in our case, then the connection with the server
is established and we can see it by printing the {\tt AppAuth} object (Authorized: TRUE).
Alternatively, we can use the {\tt hasAccess} method, which returns {\tt TRUE} if 
the access token is valid and {\tt FALSE} otherwise. 

Now that our client App is authenticated with the server we can start performing 
queries to the BaseSpace resources. 
xsa
\subsection{Users}
\label{subsec:users}

The Users resource allows the client to get basic information about the user
that is currently using the application. To query this resource we use the 
{\tt Users()} method.

<<>>=
u <- Users(aAuth)
u
@ 

The response is an object of class {\tt Users}. We can access the elements of
this class using the generic access methods. For example, we can get the Id and 
the Name element as follows:

<<>>=
Id(u)
Name(u)
@ 

Not all elements of a {\tt Response} object have methods associated to them. There 
are only a core of elements for which methods exists, see Section \ref{sec:dataModel}.
However every element of a {\tt Response} object can be accessed using the general 
access operator {\tt '\$'} and the element key/name.

<<>>=
u$Id
u$Email
u$fakeElement
@ 

When an invalid key/name is given to the access method, then {\tt NULL} is returned. 
The elements that belong to the object but have not been set can also be accessed 
and the method returns their default value. 

<<>>=
u <- Users()
u
u$Id
u$UserOwnedBy
@ 

If the access token permits one can query for a particular user ID. The ID can be 
given either as an integer or as a string (this convention for specifying IDs holds
for all API calls). 

<<>>=
Users(aAuth, id = 1463464)
Users(aAuth, id = "1463464")
@ 



\subsection{Genomes}
\label{subsec:genomes}

The Genomes resource provides access the reference genomes available in BaseSpace. 
To access this resource we use {\tt listGenomes()} and {\tt Genomes()} methods.

{\tt listGenomes()} lists all the available genomes, returning only a small summary 
for each genome. This is a general pattern across this API. Each resource implements 
a method that lists all entries/items visible to the current user, and a method which
retrieves a particular item (specified via the item ID). 

<<>>=
g <- listGenomes(aAuth, Limit = 100)
g$SpeciesName
@ 

Here we asked for at most 100 genomes available in BaseSpace. {\tt Limit = 100} is a
query parameter supported by the REST API. It tells the server that at most $100$ 
items must be returned. If missing  the dafault value of $10$ is used.

{\tt listGenomes()} returns a {\tt GenomesSummary} object which basically contains 
a {\tt Collection} object and an {\tt AppAuth} handler. We can therefore use the
{\tt Collection} interface. We can see the number of items in the returned collection
using {\tt length()} or {\tt DisplayCount} and the total number of items visible to
the current user in BaseSpace using {\tt TotalCount()}.

<<>>=
length(g)
TotalCount(g)
@ 

{\tt Collection} objects implement the {\tt [} and {\tt [[} operators for 
sellection and subsetting. Thus if we want the 3rd item from the collection we do:

<<>>=
g[[3]]
is(g[[3]], "Item")
@ 

So the {\tt [[} operator will always return an {\tt Item} object. We can subset
the collection, by giving an index:

<<>>=
g[2:4]
g[1]
@ 

The subsetting operator {\tt [} works as it works for R vectors and lists. It
returns an object of the same class of the original object.


In our case the collection size is $\Sexpr{TotalCount(g)}$, and since we specified 
{\tt Limit = 100} in the call, we retrieve the complete collection. Please check the 
\href{https://developer.basespace.illumina.com/docs/content/documentation/rest-api/api-reference}{REST API documentation}
for the complete list of query parameters. We can see bellow how different parameters 
affect the response:

<<>>=
listGenomes(aAuth, Limit = 2)
g <- listGenomes(aAuth, Offset = 5, Limit = 2, SortBy = "Build")
g
TotalCount(g) # Collection size remains constant
@ 

We can to access all the information available for a specific genome using 
the {\tt Genomes()} method. Let's assume we want to do this for the "Homo sapiens" genome, 
which has ID $4$.

<<>>=
Genomes(aAuth, id = 4)
@ 

Multiple IDs can be specified. In this case the returned value is a named list, with 
the IDs given the list' names. If a given IDs is not valid, then the respective 
element in the list is set to {\tt NULL}. At the same the server error message is shown.

<<>>=
Genomes(aAuth, id = c(4, 1, 110))
@ 

Please note that if {\tt id} has length $1$, a list with one element is returned. 
By specifying {\tt simplify = TRUE}, the list is dropped, and a {\tt Genomes} object
is returned.

<<>>=
Genomes(aAuth, id = 4, simplify = TRUE)
@ 


We can use the {\tt Genomes()} method on a {\tt GenomesSummary} object. In this case 
a {\tt Genomes} object will be returned for every item in collection.

<<>>=
Genomes(g)
@ 


\subsection{Runs}
\label{subsec:runs}

The Runs resource contains the raw data produced by the instruments, the base calls,
together with run metrics, instrument health data, and other information used for
data processing and analysis.

To list the available runs we use {\tt listRuns()} method. 

<<>>=
r <- listRuns(aAuth)
r
@ 

And as before, we can use various query parameters. For example, we can ask for 
all runs that failed. 

<<>>=
listRuns(aAuth, Statuses = "Failed") # no failed runs in our case
@ 

If we are interested in one or more runs, we use the method with the same name as
the resource, {\tt Runs()} in this case. 

<<>>=
myRun <- Runs(r[1], simplify = TRUE)
myRun
@ 

Runs have files associated with them. We can list the files associated with the selected
run using the {\tt listFiles()} method. More details on the {\tt Files} object and 
resource are given in section~\ref{subsec:files}.

<<>>=
f <- listFiles(myRun)
Name(f)
@

We can chose to select a particular type of files, base on the file extension. Here 
we want to select two BCL files.
<<>>=
listFiles(myRun, Limit = 2, Extensions = ".bcl")
@ 


\subsection{Projects}
\label{subsec:projects}

The Project resource provides a logical grouping of the Samples resource and the
AppResults resource for a given user.

Accessing the Projects resource is similar as for any most resources. There is a 
{\tt listProjects()} method for browsing the available projects and the 
{\tt Projects()} method for selecting and retrieving project data. 

<<>>=
Projects(listProjects(aAuth, Limit = 1), simplify = TRUE)
@ 

Unlike the resources seen until now, for Projects, the users may create new and/or share
existing projects. We can add a new project using the {\tt createProject()} method.

<<>>=
myNewProj <- createProject(aAuth, name = "My New Project")
myNewProj
@ 

As we can see the function failed to create a new project. This is because one needs 
additional rights, in this case the user needs to grant {\tt create project} access,
to be able to create a new resource in BaseSpace.
See \href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/using-scope}{BaseSpace Permissions}
for more details on the permission structure in BaseSpace, and Section~\ref{sec:auth}
for details on renewing permissions. 


\paragraph{Samples and AppResults}
\label{par:samples}

The Samples and AppResults resources have similar interfaces. There are no files directly
associated with a Project, but both Samples and AppResults each have files within them. 

In general, samples are the result of demultiplexing and can be considered to be holding
the input data for an App. One example of data within a Samples resource are the FASTQ
files.

The AppResults resource is used for keeping the result of an App. On top of the typical 
listing and accessing data from this resource, the user can also create new and update 
existing AppResults. The method used for adding a new AppResult instance is 
{\tt createAppResults()}. As in the case of Projects, the user need the right permission 
to be able to create a new instance. 

We can quickly browse an AppResults from the project with ID $21383369$.

<<>>=
reseq <- listAppResults(aAuth, projectId = 21383369, Limit = 1)
AppResults(reseq)
@ 

We can see that there are references to the files and genomes associated with this
resequencing result.

A more comprehensive examples, showing how to use these resources can be found in the
{\tt BaseSpaceR-QscoreApp.pdf} vignette, which one can find here:

<<eval = FALSE>>=
system.file("doc", "BaseSpaceR-QscoreApp.pdf", package = "BaseSpaceR")
@ 


\subsection{Files}
\label{subsec:files}

The Files resource provides access to files stored in BaseSpace. A file should be seen
as a data stream and associated attributes (date created, size, type, etc.).

Files are associated with specific Runs, Samples, or AppResults and the Files resource
provides the interface for manipulating these files. For each one of the above mentioned
resource, one can list the available files using the {\tt listFiles()} method. 

The method can be called using an instance of {\tt Runs}, {\tt Samples},
or {\tt AppResults}, in which case the files for the respective resource will
be listed, or using an {\tt AppAuth} handler, in which case the ID of the wanted
resource must be specified. To list the files associated with the resequncing result
selected in section~\ref{subsec:projects} we do:

<<>>=
f <- listFiles(AppResults(reseq))
TotalCount(f)
Name(f)
@ 

If we knew only the ID of the AppResults instance, then the call could have been done 
as follows:

<<>>=
identical(f, listFiles(aAuth, appResultId = Id(reseq)))
@ 

To specify the ID for Runs and Samples use {\tt runID = <ID>} and {\tt sampleId = <ID>}
respectively. 

Specific file types can be selected base on the file extension. Let's assume we are 
interested in BAM files.

<<>>=
f <- listFiles(aAuth, appResultId = Id(reseq), Extensions = ".bam")
Name(f)
@ 

Detailed information about files are available via the {\tt Files} method. One can
call the function using a {\tt FilesSummary} object (the object returned by 
{\tt listFiles()}) or using the {\tt AppAuth} handler and the file ID.

<<>>=
Files(f)
@ 

Access to the files attributes and the data stream is restricted and requires
additional permissions. The equivalent of the above call, for an {\tt AppAuth} 
handler is: {\tt Files(aAuth, id = Id(f))}. Please note that {\tt id} is the 
ID of a file regardless of the resource it belongs to. 

There is a much richer API for the Files resource. One can download the selected files, 
upload a file and set the files attributes. Multiple file uploads are also supported. 
However all these operations require additional permissions and are out of the scope 
of this document. Please see {\tt BaseSpaceR-QscoreApp.pdf} for more elaborate examples 
using files.


\paragraph{Coverage and Variants}
\label{par:samples}

Certain files, in particular VCF and BAM files, have additional information available.
BaseSpace offers to separate resources for these two types, Coverage and Variants.

The Coverage resource is used to provide mean read coverage depth in a particular
chromosomal region. Querying the resources we get the coverage depth histogram.
This resource is at this moment implemented only for BAM files. We can find the BAM files
in an AppResults instance.
<<>>=
bamFiles <- listFiles(AppResults(reseq), Extensions = ".bam")
Name(bamFiles)
Id(bamFiles)
bamFiles
@ 

There are two functions implemented for this resource, {\tt getCoverageStats()} and
{\tt getCoverage()}. 

<<>>=
getCoverageStats(aAuth, id = Id(bamFiles), "phix")
@ 

Unfortunately, the user needs to grant read access to the selected AppResults instance, 
to be able to access the raw BAM data. 


The Variants resource provides access to variants within a VCF file. It allows for 
efficient querying the variants of a particular chromosomal region. The R API 
functions to interact with this resource are {\tt getVariantSet()} and 
{\tt getVariants()}. As with the Coverage resource, one needs additional 
permission to access this resource. 

To find VCF files, we query the AppResults resource and select files base on 
the file extension. 

<<>>=
vcfs <- listFiles(AppResults(reseq), Extensions = ".vcf")
Name(vcfs)
Id(vcfs)
vcfs
@ 

And as above, we are not able to access this resource, give the restricted 
access token we are using throughout this document.

<<eval = FALSE>>=
getVariants(aAuth, Id(vcfs)[1], chrom = "chr", EndPos = 1000000L, Limit = 5)
@ 



%%\clearpage




\section{Authentication}
\label{sec:auth}

The authentication and communication between the client, the R application, and the 
server, the BaseSpace REST server, is handled by an object of class {\tt AppAuth}.

It is easy to create an {\tt AppAuth} instance, and there a few options for doing this.
However, before going further and detail the interface this object provides, we need to
clarify the authentication process. First we advise developers to familiarize with 
\href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/authenticating}{BaseSpace authentication}
and the OAuth v2 workflow. 

To start the authentication process the developer must have the {\tt client\_id} 
and the {\tt client\_secret}. These are available in 
\href{https://developer.basespace.illumina.com/apps}{BaseSpace's application management} screen of your app.
If this is the first time you hear about {\tt client\_id} and {\tt client\_secret}
please read through \href{https://developer.basespace.illumina.com/docs/content/documentation/getting-started/overview#Steps_for_developing_your_first_App}{Steps for developing your first App} 
section before going forward with this document.

BaseSpaceR offers the following options for an App to authenticate with BaseSpace.
\begin{itemize}
\item Use a pre-generated access token.
\item Use the OAuth v2 process. This is the recommended option, but this requires
  the user interacting directly with a Web browser. 
\item Use the AppSessions and \href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/app-triggering}{BaseSpace Application Triggering} workflow.
  However this requires a web server to process App launch. {\it [under development]}
\end{itemize}


\subsection{The OAuth v2 workflow}

To start the authentication process we need to instantiate an {\tt AppAuth} object
with the {\tt client\_id} and the {\tt client\_secret}.

<<>>=
myAppClientId <- "aaaaa8acb37a441fa71af5072fd7432b"
myAppClientSecret <- "bbbbb8acb37a441fa71af5072fd7432b"

aAuth <- AppAuth(client_id = myAppClientId,
                 client_secret = myAppClientSecret,
                 scope = "create global")
@ 

The above code will show a server error, which is expected since the provided 
{\tt client\_id} and {\tt client\_secret} are fake. However, the {\tt AppAuth} 
instance is valid, just not authenticated with the server.

Printing the handler will show basic information. Note that since there is no
valid access token associated with this object we get {\it Authorized: FALSE}.

The permission type is specified using the {\tt scope} parameter. 
See \href{https://developer.basespace.illumina.com/docs/content/documentation/authentication/using-scope}{BaseSpace Permissions}
for a comprehensive description on how to define the {\tt scope}.
If {\tt scope} parameter is missing the default setting, {\tt browse~global} is used.


If the specified {\tt client\_id} and {\tt client\_secret} were valid, the {\tt AppAuth()}
constructor would have initiated the authentication process, in which case the user is
shown the following message:
\begin{Schunk}
\begin{Soutput}
Perform OAuth authentication using the following URI:
    https://basespace.illumina.com/oauth/device?code=xxxxx
\end{Soutput}
\end{Schunk}

The App user needs to open the URI in a browser and perform the authentication. The 
app will have to idle until further user input. 


Alternatively one can instantiate an {\tt AppAuth} object without triggering the
authentication process. This is achieved by specifying {\tt doOAuth = FALSE} in 
the function call.

<<>>=
aAuth <- AppAuth(client_id = myAppClientId,
                 client_secret = myAppClientSecret,
                 scope = "read global", 
                 doOAuth = FALSE) 
aAuth
@ 


The OAuth authentication process can be triggered at any point using the
{\tt initializeAuth()} method. We can also specify a new scope when calling the function.
In this case, the previous scope associated with the {\tt aAuth} handler will be updated. 
For example, an empty scope, allow us to access the user information. 

<<>>=
res <- initializeAuth(aAuth, scope = character())
res
@ 

The function returns a list with two entries. The URI and the device code. This can
be used by the developer to automatically launch a browser, or create custom messages
for the user.


 
\paragraph{Obtaining an Access Token}

Once the user has granted access using the OAtuh v2 authentication dialog box, 
we can request the access token from the server and update the {\tt aAuth} handler. 
This is achieved by calling the {\tt requestAccessToken()} function.

<<eval = FALSE>>=
requestAccessToken(aAuth)
hasAccess(aAuth)
@ 

If the request is successful, the following message is shown {\it Access token
  successfully acquired!}. Calling {\tt hasAccess()} or printing the
{\tt AppAuth} instance will show 'Authorized: TRUE'. If the request fails, the response
returned by the REST API is show. For example, if the user didn't authorized the
request we get the following message:
\begin{Schunk}
\begin{Soutput}
BadRequest
{
  "error" : "authorization_pending",
  "error_description" : "User has not yet approved the access request"
} 
\end{Soutput}
\end{Schunk}


\subsection{Using a pre-generated access token}

One can instantiate an {\tt AppAuth} object using a pre-generated access token. 
To pre-generate an access token we can use the above described OAuth v2 workflow 
and save the access token for further use, or use other tools available in BaseSpace.

A pre-generated access token with restricted permissions can be obtained from the 
{\tt aAuth} data.

<<>>=
data(aAuth)
app_access_token <- aAuth$access_token
@ 

{\tt app\_access\_token} contains the $32$ character string access token. We can 
now instantiate a new handler as follows:

<<>>=
newAuth <- AppAuth(access_token = app_access_token)
newAuth
@ 

If the access token is valid, which should be in our case, the connection with the
server is established and we can see it by printing the {\tt AppAuth} object
{\it Authorized:    TRUE}.

Please note that it does not make sense to specify a scope because the scope is already 
encapsulated in the access token. Also, the {\tt client\_id} and the {\tt client\_secret}
are not required in this case, given that once the access token is available they are not 
needed to communicate with the server. However, they can be specified together with
the pre-generated access token.

<<>>=
newAuth <- AppAuth(access_token = app_access_token, 
                   client_secret = myAppClientSecret,
                   client_id = myAppClientId)
newAuth
@ 

The advantage of having the {\tt client\_id} and the {\tt client\_secret} is that we
can re-initiate the OAuth v2 process at any point, and update the handler scope.


\clearpage

\section{Session Information}

The version number of R and packages loaded for generating the vignette were:

<<echo=FALSE,results=tex>>=
toLatex(sessionInfo())
@


\end{document}