From 8f341e3004d9961e50c3c70ec08cd55c023110b4 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Thu, 7 Jan 2016 14:45:04 -0300 Subject: [PATCH 01/89] Initial commit --- .gitignore | 12 ++++++++++++ LICENSE | 22 ++++++++++++++++++++++ README.md | 1 + 3 files changed, 35 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..32858aad --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..a7f9e41d --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Auth0 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/README.md b/README.md new file mode 100644 index 00000000..a1f4774d --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# auth0-api-java From ce87538bdf31576c5226729d58c7f93bf33fa016 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 7 Jan 2016 17:53:30 -0300 Subject: [PATCH 02/89] Project structure --- .gitignore | 20 +++ build.gradle | 10 ++ core/build.gradle | 5 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 52271 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 164 +++++++++++++++++++++++ gradlew.bat | 90 +++++++++++++ settings.gradle | 2 + 8 files changed, 297 insertions(+) create mode 100644 build.gradle create mode 100644 core/build.gradle create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle diff --git a/.gitignore b/.gitignore index 32858aad..ab746e30 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,23 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +# IntelliJ IDEA / Android Studio +.idea +*.iml +local.properties + +# Gradle files +.gradle/ +build/ +/*/build/ + +# Generated files +bin/ +gen/ + +# Log Files +*.log + +# MacOS +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..1e37bc7e --- /dev/null +++ b/build.gradle @@ -0,0 +1,10 @@ +allprojects { + version = 'com.auth0.java' + group = '0.1-SNAPSHOT' + + repositories { + mavenCentral() + jcenter() + } +} + diff --git a/core/build.gradle b/core/build.gradle new file mode 100644 index 00000000..b9f81c07 --- /dev/null +++ b/core/build.gradle @@ -0,0 +1,5 @@ +apply plugin: 'java' + +dependencies { + testCompile 'junit:junit:4.12' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..30d399d8d2bf522ff5de94bf434a7cc43a9a74b5 GIT binary patch literal 52271 zcmafaW0a=B^559DjdyI@wy|T|wr$(CJv+9!W822gY&N+!|K#4>Bz;ajPk*RBjZ;RV75EK*;p4^!@(BB5~-#>pF^k0$_Qx&35mhPenc zNjoahrs}{XFFPtR8Xs)MInR7>x_1Kpw+a8w@n0(g``fp7GXFmo^}qAL{*%Yt$3(FfIbReeZ6|xbrftHf0>dl5l+$$VLbG+m|;Uk##see6$CK4I^ ziDe}0)5eiLr!R5hk6u9aKT36^C>3`nJ0l07RQ1h438axccsJk z{kKyd*$G`m`zrtre~(!7|FcIGPiGfXTSX`PzlY^wY3ls9=iw>j>SAGP=VEDW=wk2m zk3%R`v9(7LLh{1^gpVy8R2tN#ZmfE#9!J?P7~nw1MnW^mRmsT;*cyVG*SVY6CqC3a zMccC8L%tQqGz+E@0i)gy&0g_7PV@3~zaE~h-2zQ|SdqjALBoQBT2pPYH^#-Hv8!mV z-r%F^bXb!hjQwm2^oEuNkVelqJLf029>h5N1XzEvYb=HA`@uO_*rgQZG`tKgMrKh~aq~ z6oX{k?;tz&tW3rPe+`Q8F5(m5dJHyv`VX0of2nf;*UaVsiMR!)TjB`jnN2)6z~3CK@xZ_0x>|31=5G$w!HcYiYRDdK3mtO1GgiFavDsn&1zs zF|lz}sx*wA(IJoVYnkC+jmhbirgPO_Y1{luB>!3Jr2eOB{X?e2Vh8>z7F^h$>GKmb z?mzET;(r({HD^;NNqbvUS$lhHSBHOWI#xwT0Y?b!TRic{ z>a%hUpta3P2TbRe_O;s5@KjZ#Dijg4f=MWJ9euZnmd$UCUNS4I#WDUT2{yhVWt#Ee z?upJB_de&7>FHYm0Y4DU!Kxso=?RabJ*qsZ2r4K8J#pQ)NF?zFqW#XG1fX6dFC}qh z3%NlVXc@Re3vkXi*-&m)~SYS?OA8J?ygD3?N}Pq zrt_G*8B7^(uS7$OrAFL5LvQdQE2o40(6v`se%21Njk4FoLV-L0BN%%w40%k6Z1ydO zb@T(MiW@?G-j^j5Ypl@!r`Vw&lkJtR3B#%N~=C z@>#A{z8xFL=2)?mzv;5#+HAFR7$3BMS-F=U<&^217zGkGFFvNktqX z3z79GH^!htJe$D-`^(+kG*);7qocnfnPr^ieTpx&P;Z$+{aC8@h<0DDPkVx`_J~J> zdvwQxbiM1B{J6_V?~PNusoB5B88S%q#$F@Fxs4&l==UW@>9w2iU?9qMOgQWCl@7C* zsbi$wiEQEnaum!v49B_|^IjgM-TqMW!vBhhvP?oB!Ll4o-j?u3JLLFHM4ZVfl9Y_L zAjz@_3X5r=uaf|nFreX#gCtWU44~pA!yjZNXiZkoHhE$l@=ZTuxcLh53KdMOfanVe zPEX(#8GM7#%2*2}5rrdBk8p#FmzpIC>%1I9!2nRakS|^I*QHbG_^4<=p)(YOKvsTp zE#DzUI>Y&g)4mMaU6Bhrm8rSC{F_4J9sJlF0S5y5_=^l!{?W_n&SPj&7!dEvLzNIRMZBYyYU@Qftts7Zr7r>W- zqqk46|LEF|&6bn#CE~yMbiF&vEoLUA(}WzwmXH_=<~|I(9~{AE$ireF7~XBqPV2)* zcqjOCdi&>tUEuq31s(|TFqx>Wuo(ooWO(sd!W~Hu@AXg=iQgq^O3Lv9xH$vx*vrgDAirQqs9_DLS1e45HcUPdEMziO?Mm1v!)n93L%REy=7 zUxcX!jo!vyl_l0)O(Y~OT``;8mB(tcf}`Rh^weqPnDVDe-ngsZ~C z`onh0WLdaShAAb-3b{hT5ej9a$POQ9;RlPy}IYzKyv+8-HzB7fV!6X@a_T61qZ zWqb&&ip*@{;D-1vR3F2Q&}%Q>TFH&2n?2w8u8g=Y{!|;>P%<@AlshvM;?r7I)yXG% z^IpXZ(~)V*j^~sOG#cWCa+b8LC1IgqFx+Mq$I`6VYGE#AUajA9^$u-{0X#4h49a77 zH>d>h3P@u!{7h2>1j+*KYSNrKE-Q(z`C;n9N>mfdrlWo$!dB35;G4eTWA}(aUj&mNyi-N+lcYGpA zt1<~&u`$tIurZ2-%Tzb1>mb(~B8;f^0?FoPVdJ`NCAOE~hjEPS) z&r7EY4JrG~azq$9$V*bhKxeC;tbBnMds48pDuRy=pHoP*GfkO(UI;rT;Lg9ZH;JU~ zO6gTCRuyEbZ97jQyV7hM!Nfwr=jKjYsR;u8o(`(;qJ(MVo(yA<3kJximtAJjOqT=3 z8Bv-^`)t{h)WUo&t3alsZRJXGPOk&eYf}k2JO!7Au8>cvdJ3wkFE3*WP!m_glB-Rt z!uB>HV9WGcR#2n(rm=s}ulY7tXn5hC#UrNob)-1gzn-KH8T?GEs+JBEU!~9Vg*f6x z_^m1N20Do}>UIURE4srAMM6fAdzygdCLwHe$>CsoWE;S2x@C=1PRwT438P@Vt(Nk` zF~yz7O0RCS!%hMmUSsKwK$)ZtC#wO|L4GjyC?|vzagOP#7;W3*;;k?pc!CA=_U8>% z%G^&5MtFhvKq}RcAl))WF8I#w$So?>+_VEdDm_2=l^K320w~Bn2}p+4zEOt#OjZ6b zxEYoTYzvs$%+ZYwj;mZ@fF42F1-Hb<&72{1J)(D~VyVpo4!dq259t-_Oo3Yg7*R`N zUg!js4NRyfMbS*NLEF}rGrlXz0lHz))&&+B#Tdo@wlh-Q8wr7~9)$;s9+yJH0|m=F zSD9mUW>@HLt}mhAApYrhdviKhW`BfNU3bPSz=hD+!q`t*IhG+Z4XK;_e#AkF5 z&(W7iUWF4PNQ+N!-b-^3B$J4KeA1}&ta@HK=o2khx!I&g#2Y&SWo-;|KXDw!Xb)mP z$`WzPA!F(h*E=QP4;hu7@8J&T|ZPQ2H({7Vau6&g;mer3q?1K!!^`|0ld26 zq|J&h7L-!zn!GnYhjp`c7rG>kd1Y%8yJE9M0-KtN=)8mXh45d&i*bEmm%(4~f&}q@ z1uq)^@SQ~L?aVCAU7ZYFEbZ<730{&m?Un?Q!pxI7DwA^*?HloDysHW{L!JY!oQ8WMK(vT z@fFakL6Ijo$S$GH;cfXcoNvwVc8R7bQnOX2N1s$2fbX@qzTv>748In?JUSk@41;-8 zBw`fUVf$Jxguy{m1t_Z&Q6N$Ww*L9e%6V*r3Yp8&jVpxyM+W?l0km=pwm21ch9}+q z$Z&eb9BARV1?HVgjAzhy);(y1l6)+YZ3+u%f@Y3stu5sSYjQl;3DsM719wz98y4uClWqeD>l(n@ce)pal~-24U~{wq!1Z_ z2`t+)Hjy@nlMYnUu@C`_kopLb7Qqp+6~P=36$O!d2oW=46CGG54Md`6LV3lnTwrBs z!PN}$Kd}EQs!G22mdAfFHuhft!}y;8%)h&@l7@DF0|oy?FR|*E&Zuf=e{8c&hTNu# z6{V#^p+GD@A_CBDV5sM%OA*NwX@k1t?2|)HIBeKk(9!eX#J>jN;)XQ%xq^qVe$I}& z{{cL^a}>@*ZD$Ve)sJVYC!nrAHpV~JiCH3b7AQfAsEfzB$?RgU%+x7jQ_5XQ8Gf*N`i<1mZE zg6*_1dR3B`$&9CxHzk{&&Hf1EHD*JJF2glyBR+hBPnwP@PurN`F80!5{J57z;=kAc za65ouFAve7QEOmfcKg*~HZ04-Ze%9f)9pgrVMf7jcVvOdS{rf+MOsayTFPT}3}YuH z$`%^f$}lBC8IGAma+=j9ruB&42ynhH!5)$xu`tu7idwGOr&t=)a=Y2Sib&Di`^u9X zHQ=liR@by^O`ph|A~{#yG3hHXkO>V|(%=lUmf3vnJa#c%Hc>UNDJZRJ91k%?wnCnF zLJzR5MXCp)Vwu3Ew{OKUb?PFEl6kBOqCd&Qa4q=QDD-N$;F36Z_%SG}6{h2GX6*57 zRQIbqtpQeEIc4v{OI+qzMg_lH=!~Ow%Xx9U+%r9jhMU=7$;L7yJt)q+CF#lHydiPP zQSD=AtDqdsr4G!m%%IauT@{MQs+n7zk)^q5!VQrp?mFajX%NQT#yG9%PTFP>QNtfTM%6+b^n%O`Bk74Ih| zb>Fh1ic{a<8g<{oJzd|@J)fVVqs&^DGPR-*mj?!Z?nr<f)C8^oI(N4feAst}o?y z-9Ne339xN7Lt|Tc50a48C*{21Ii$0a-fzG1KNwDxfO9wkvVTRuAaF41CyVgT?b46; zQvjU!6L0pZM%DH&;`u`!x+!;LaPBfT8{<_OsEC5>>MoJQ5L+#3cmoiH9=67gZa;rvlDJ7_(CYt3KSR$Q#UR*+0hyk z>Dkd2R$q~_^IL2^LtY|xNZR(XzMZJ_IFVeNSsy;CeEVH|xuS#>itf+~;XXYSZ9t%1moPWayiX=iA z!aU~)WgV!vNTU=N;SpQ((yz#I1R#rZ&q!XD=wdlJk4L&BRcq(>6asB_j$7NKLR%v; z9SSp$oL7O|kne`e@>Bdf7!sJ*MqAtBlyt9;OP3UU1O=u6eGnFWKT%2?VHlR86@ugy z>K)(@ICcok6NTTr-Jh7rk=3jr9`ao!tjF;r~GXtH~_&Wb9J^ zd%FYu_4^3_v&odTH~%mHE;RYmeo+x^tUrB>x}Is&K{f+57e-7Y%$|uN%mf;l5Za95 zvojcY`uSCH~kno zs4pMlci*Y>O_pcxZY#?gt1^b-;f(1l9}Ov7ZpHtxfbVMHbX;579A>16C&H5Q>pVpH5LLr<_=!7ZfX23b1L4^WhtD?5WG;^zM}T>FUHRJv zK~xq88?P);SX-DS*1LmYUkC?LNwPRXLYNoh0Qwj@mw9OP&u{w=bKPQ)_F0-ptGcL0 zhPPLKIbHq|SZ`@1@P5=G^_@i+U2QOp@MX#G9OI20NzJm60^OE;^n?A8CH+XMS&3ek zP#E7Y==p;4UucIV{^B`LaH~>g6WqcfeuB#1&=l!@L=UMoQ0$U*q|y(}M(Y&P$Xs&| zJ&|dUymE?`x$DBj27PcDTJJn0`H8>7EPTV(nLEIsO&9Cw1Dc&3(&XFt9FTc{-_(F+ z-}h1wWjyG5(ihWu_3qwi; zAccCjB3fJjK`p=0VQo!nPkr0fT|FG;gbH}|1p`U>guv9M8g2phJBkPC`}ISoje6+? zvX|r5a%Y-@WjDM1&-dIH2XM}4{{d&zAVJQEG9HB8FjX&+h*H=wK=xOgNh8WgwBxW+ z0=^CzC4|O_GM>^_%C!!2jd&x*n2--yT>PZJ`Mok6Vf4YFqYp@a%)W}F4^DpKh`Cr7 z{>Z7xw-4UfT@##s#6h%@4^s^7~$}p2$v^iR5uJljApd9%#>QuxvX+CSZv18MPeXPCizQ*bm);q zWhnVEeM}dlCQP*^8;Q7OM|SSgP+J;DQy|bBhuFwJ2y*^|dBwz96-H;~RNsc}#i= zwu`Tp4$bwRVb7dxGr_e1+bJEc=mxLxN_f>hwb#^|hNdewcYdqXPrOxDE;|mP#H|a% z{u8#Vn}zVP(yJ}+-dx;!8<1in=Q8KsU%Q5CFV%5mGi8L;)*m%Vs0+S`ZY(z7aZ$VCjp?{r>C<9@$zVN;LVhxzPEdDPdb8g<)pckA z?mG@Ri>ode(r|hjNwV#*{!B^l2KO@4A+!X;#PW#?v2U!ydYIFHiXC3>i2k7{VTfji>h z8-(^;x!>f)Qh$mlD-z^1Nxu})XPbN=AUsb%qhmTKjd=1BjKr(L9gb1w4Y8p+duWfS zU>%C>*lCR@+(ku!(>_SA6=4CeM|$k4-zv|3!wHy+H&Oc$SHr%QM(IaBS@#s}O?R7j ztiQ>j^{X)jmTPq-%fFDxtm%p|^*M;>yA;3WM(rLV_PiB~#Eaicp!*NztJNH;q5BW$ zqqlfSq@C0A7@#?oRbzrZTNgP1*TWt(1qHii6cp5U@n|vsFxJ|AG5;)3qdrM4JElmN z+$u4wOW7(>$mMVRVJHsR8roIe8Vif+ml3~-?mpRos62r0k#YjdjmK;rHd{;QxB?JV zyoIBkfqYBZ!LZDdOZArQlgXUGmbpe7B-y7MftT;>%aM1fy3?^CuC{al$2-tfcA?d) z<=t7}BWsxH3ElE^?E&|f{ODX&bs+Ax>axcdY5oQ`8hT)YfF%_1-|p*a9$R~C=-sT| zRA~-Q$_9|G(Pf9I+y!zc>fu)&JACoq&;PMB^E;gIj6WeU=I!+scfSr}I%oD1fh+AQ zB^Q^b@ti5`bhx+(5XG5*+##vV>30UCR>QLYxHYY~k!AR`O6O_a3&wuW61eyHaq;HL zqy@?I*fmB)XY;Z@RH^IR|6m1nwWv>PDONtZV-{3@RkM_JcroRNLTM9?=CI}l%p86A zdxv|{zFWNI;L8K9hFSxD+`-pwvnyS|O?{H-rg6dPH<3oXgF0vU5;~yXtBUXd>lDs~ zX!y3-Pr9l;1Q^Z<15_k1kg|fR%aJKzwkIyED%CdxoXql=^QB;^*=2nVfi{w?0c@Dj z_MQEYjDpf^`%)$|4h>XnnKw05e5p4Jy69{uJ5p|PzY+S?FF~KWAd0$W<`;?=M+^d zhH&>)@D9v1JH2DP?tsjABL+OLE2@IB)sa@R!iKTz4AHYhMiArm)d-*zitT+1e4=B( zUpObeG_s*FMg$#?Kn4%GKd{(2HnXx*@phT7rEV?dhE>LGR3!C9!M>3DgjkVR>W)p3 zCD0L3Ex5-#aJQS6lJXP9_VsQaki5#jx}+mM1`#(C8ga~rPL{2Z;^^b+0{X)_618Sw z0y6LTkk;)quIAYpPY{)fHJLk?)(vxt?roO24{C!ck}A)_$gGS>g!V^@`F#wg+%Cok zzt6hJE|ESs@S^oHMp3H?3SzqBh4AN(5SGi#(HCarl^(Jli#(%PaSP9sPJ-9plwZv{ z1lkTGk4UAXYP^>V+4;nQ4A~n-<+1N)1lPzXIbG{Q;e3~T_=Trak{WyjW+n!zhT*%)q?gx zTl4(Gf6Y|ALS!H$8O?=}AlN=^3yZCTX@)9g5b_fif_E{lWS~0t`KpH8kkSnWWz+G1 zjFrz}gTnQ2k-`oag*031Nj7=MZfP}gvrNvv_crWzf9Cdzv^LyBeEyF2#hGg8_C8jW)NCAhsm2W_P21DeX7x$4EDD){~vBiLoby=d+&(;_f(?PMfamC zI_z%>Nq-rC%#z#1UC49j4@m63@_7LWD$ze=1%GPh`%@PB7yGH6Zh=1#L%&%hU7z%Y zs!IN(ef@!+|1YR28@#kw^XR= zxB$*nNZm7Y@L0&IlmoN}kEI?dBee+z+!MWCy+e4P4MYpOgr}2Q(wnR1ZiA>5_P*Cg zB4BMlcx?(v*+V3O+p~Buk;wIN6v!Ut?gYpl+KFu~elf}{E4`9+lcR0k$bC>+I zWxO5jD8sYPbMS)4c3i2UojI4T7uzE*Zz;POw{0d0`*iHJ%(Pb=sa^pV{t_JtHoPeC zX+t_k*=D%+Sv#+5CeoRfI)G`T90~AE@K9RaFR%8*w#*x9>H$ahFd>PUg_zP`VVPSR zr#Rb;I--8Rq;eTBju;dx2cmZ9Al>aiDY z#7(4S(A#aRvl7jm78sQ+O^S5eUS8|W%5@Pt9fm?J=r`~=l-gdv(LB~C-Gi#srwEDQ z4cCvA*XiRj9VDR6Ccy2k(Nvxic;~%YrfNeWl$cJpa%WO_4k?wxKZ{&`V#!&#jV@x+ z7!!YxOskc;cAF~`&aRWp8E)fnELtvb3-eHkeBPb~lR&iH=lZd^ZB(T6jDg5PnkJQFu9? z+24ww5L%opvEkE$LUHkZDd0ljo!W}0clObhAz`cPFx2)X3Sk91#yLL}N6AE0_O`l| z7ZhaKuAi7$?8uuZAFL(G0x3wE<-~^neGm=*HgJa(((J;yQI$NB)J;i0?vr`M1v+R? zd+{rD^zK}0Gi!2lXo0P+jVQ$HNYn^sRMONYVZPPT@enUb1pHHYgZMo5GN~SIz*;gv z1H<4(%53!6$4+VX_@Kp!>A9wwo{(KdWx)ja>x3&4=H(Urbn?0Vh}W3%ly5SgJ<+X5?N7-B=byoKyICr>3 zIFXe;chMk7-cak~YKL8Bf>VbZbX{5L9ygP_XS?oByNL*zmp8&n9{D42I^=W=TTM4X zwb_0axNK?kQ;)QUg?4FvxxV7L@sndJL0O12M6TMorI&cAL%Q464id6?Tbd_H!;=SRW9w2M*wc00yKVFslv|WN( zY7=Yikt+VY@DpzKq7@z_bVqr7D5B3xRbMrU5IO7;~w2nNyP7J_Gp>>7z?3!#uT4%-~h6)Ee1H z&^g}vZ{g}DIs@FDzE$QG_smSuEyso@I#ID3-kkYXR=nYuaa0{%;$WzZC@j)MDi+jC z!8KC;1mGCHGKr>dR;3;eDyp^0%DH`1?c7JcsCx$=m(cs^4G& zl@Fi8z|>J`^Z-faK{mhsK|;m%9?luacM+~uhN@<20dfp4ZN@qsi%gM67zZ`OHw=PE zr95O@U(HheB7OBYtyF=*Z5V&m?WDvIQ`edwpnT?bV`boB z!wPf&-@7 z0SoTB^Cy>rDHm%^b0cv@xBO%02~^=M79S}TG8cbVhj72!yN_87}iA1;J$_xTb+Zi@76a{<{OP0h&*Yx`U+mkA#x3YQ} zPmJsUz}U0r?foPOWd5JFI_hs_%wHNa_@)?(QJXg>@=W_S23#0{chEio`80k%1S?FWp1U;4#$xlI-5%PEzJcm zxjp$&(9f2xEx!&CyZZw|PGx&4$gQbVM|<2J&H7rpu;@Mc$YmF9sz}-k0QZ!YT$DUw z_I=P(NWFl!G-}aofV?5egW%oyhhdVp^TZH%Q4 zA2gia^vW{}T19^8q9&jtsgGO4R70}XzC-x?W0dBo+P+J8ik=6}CdPUq-VxQ#u4JVJ zo7bigUNyEcjG432-Epy)Rp_WDgwjoYP%W|&U~Gq-r`XK=jsnWGmXW6F}c7eg;$PHh>KZ@{cbTI<`ZP>s(M@zy=aHMA2nb(L0COlVcl8UXK+6`@Di+Wai;lJf^7s6V%NkKcad zDYY%2utqcw#CJFT9*V9U_{DyP&VYb)(6y`Z%Rq& z!PTtuI#psBgLPoNu{xvs^y26`oY;p!fE=bJW!cP^T>bUE*UKBV5Bd%!U{Q5{bKwN> zv)pn@Oc{6RyIS>!@Yvkv+hVLe+bmQ6fY2L}tT)Vbewg8`A`PFYyP+@QmL?b{RED;; zR6fwAAD}Ogejah(58bv{VG&WJhll7X-hjO9dK`8m5uFvthD1+FkJtT_>*{yKA(lXx zKucHMz#F_G)yTJw!)I3XQ7^9ydSlr9D)z?e*jKYE?xTKjR|ci30McU^4unzPsHGKN zMqwGd{W_1_jBQ_oeU^4!Ih}*#AKF%7txXZ0GD}Jzcf+i*?WLAe6#R_R-bSr17K%If z8O2SwYwMviXiJ?+$% zse=E~rK*PH@1Md4PFP)t(NhV%L3$657FUMap?fugnm3|N z79w3|qE%QyqZB}2WG&yc>iOaweUb`5o5p9PgyjqdU*sXP=pi$-1$9fGXYgS2?grS6 zwo#J~)tUTa0tmGNk!bg*Pss&uthJDJ$n)EgE>GAWRGOXeygh;f@HGAi4f){s40n?k z=6IO?H1_Z9XGzBIYESSEPCJQrmru?=DG_47*>STd@5s;1Y|r*+(7s4|t+RHvH<2!K z%leY$lIA{>PD_0bptxA`NZx-L!v}T4JecK#92kr*swa}@IVsyk{x(S}eI)5X+uhpS z8x~2mNLf$>ZCBxqUo(>~Yy4Z3LMYahA0S6NW;rB%)9Q z8@37&h7T$v2%L|&#dkP}N$&Jn*Eqv81Y*#vDw~2rM7*&nWf&wHeAwyfdRd%`>ykby zC*W9p2UbiX>R^-!H-ubrR;5Z}og8xx!%)^&CMl(*!F%or1y&({bg?6((#og-6Hey&3th3S%!n3N|Z2ZCZHJxvQ9rt zv|N#i*1=qehIz_=n*TWC6x-ab)fGr8cu!oYV+N)}3M;H4%$jwO>L!e53sxmJC~;O; zhJw|^&=2p!b8uk{-M|Z*J9n0{(8^>P+Y7vlFLc8#weQMg2iB8MFCe-*^BJV6uVWjg zWZe{-t0f67J<|IIn4{wsKlG*Amy{-yOWMMW)g}rh>uEE;jbkS-om>uAjeTzCg51683UTmY4+yT zW!qe`?~F{~1Y>mPJ9M0hNRBW$%ZwOA-NdIeaE6_K z>y8D3tAD7{3FouIXX9_MbY;zq%Ce0}VmT;aO~=*Mk4mflb_i4CApxEtZ^TDNoOzy_ z-eIE(&n1Vz*j&(BjO*fVvSCozTJU4?tWC8m4=d|D{WV0k+0M2!F1=T}z7V4-JA*y( z!;H(sOBmg=%7p&LLf%z%>VgtdN6jl2y95aXY}v9U;m~YWx{2#lwLpEJWGgs`sE*15 zvK`DtH-Q^ix>9@qVG+d*-C{lYPBbts1|%3!CkLP1t4iz%LO-di4lY%{8>jd{turVrD*_lLv!ShQC~S#SXjCO?##c zh2aZKVAHDf1sQpZiH^C7NRu?44JuEp?%W4-?d;Dg z;`gKA9$oC{WlQuT?fex!ci3GJhU;1J!YLHbyh8B-jsZ~pl59LGannKg9}1qxlbOOq zaJhTl zEJ`2Xd_ffdK^EE1v>8kUZG`eMXw(9S+?Lxx#yTUo?WdV}5kjC|glSJqX zv8RO|m#Ed@hW=};Yfl&2_@11Xm}pz0*SRx%OH_NODo@>e$cMAv(0u`~Yo|qbQ~mzA zMKt^U+GIXKH^xuD9n}NfU|?ZTOSS>XJwlg`lYHgea)!ZR?m^=oj+qyKBd6SJvPZk* zwc-2$b%%V~k$5{=(rG!OcR{;u2V3um|C+oT5F?rt`CER|iU9-!_|GxMe^!f$d6*iz z{?~JnR84mS+!gFUxugG?g9uGFI(?Q0SADS8=n=#aCK^`6@rm4r=LJTBm;)cY zm_6c5!ni$SWFOuj36eKau>6=kl_p=-7>VL_fJuJZI}0=3kASf|t;B~;Mt(vuhCU+c zKCF@SJ5#1>8YLfe{pf?sH*v6C)rOvO1~%@+wN}#>dkcrLw8U@xAySc{UeaP?7^AQ5 zmThfw^(i@*GMlM!xf+dzhRtbo8#;6Ql_s$t15q%*KeCm3`JrXnU*T^hV-aGX)bmxF z;O%jGc{6G+$gZ$YvOM2bZ!?>X<^-D zbT+YCx722}NY88YhKnw?yjF1#vo1v+pjId;cdyT*SH@Bc>6(GV*IBkddKx%b?y!r6 z=?0sTwf`I_Jcm(J8D~X@ESiO`X&i53!9}5l}PXzSYf9 zd&=h`{8BP-R?E*Nk$yzSSFhz2uVerdhbcCWF{S7reTkzXB;U@{9`hvC0AscwoqqU( zKQavt5OPm9y1UpKL%O(SWSSX=eo2rky_8jJ-ew7>iw~T=Xrt3EEzc!slebwG)FrE> z>ASkjJk%#@%SFWs-X4)?TzbBtDuwF#;WVw}?(K`UYqm`3vKbFKuqQ8uL2Y5}%T0y5 zia#E?tyZgnuk$LD^ihIn(i~|1qs(%NpH844QX-2S5E)E7lSM=V56o>5vLB^7??Vy_ zgEIztL|85kDrYF(VUnJ$^5hA;|41_6k-zO#<7gdprPj;eY_Et)Wexf!udXbBkCUA)>vi1E!r2P_NTw6Vl6)%M!WiK+jLRKEoHMR zinUK!i4qkppano|OyK(5p(Dv3DW`<#wQVfDMXH~H(jJdP47Y~`% z#ue|pQaVSv^h#bToy|pL!rWz8FQ53tnbEQ5j#7op?#c#(tj@SM2X*uH!;v8KtS5Fo zW_HE8)jSL zYO}ii#_KujRL4G*5peU)-lDW0%E}!YwL#IKUX_1l9ijy~GTFhO?W^=vEBe?m+tvBe zLaGWcoKg==%dO#6R}`U0>M)2+{b*~uamlaUNN<_NVZTGY4-(ORqK6|HvKFMKwp6^L zR+MC^`6^|^=u^Do;wy8mUp^Oct9~=vQ74vfO-m&Q0#~-mkqkpw&dMkVJ(So<)tf3h z46~mW_3T@Mzh<2XZYO7@F4j|BbhhXjs*hayIjTKyGoYO}`jEFn^!4Y! zL30ubp4U(r>Nx&RhaJkGXuRe%%f%D;1-Zdw2-9^Mq{rP-ZNLMpi~m+v?L=sPSAGcc z{j+Y!3CVrm);@{ z;T?sp1|%lk1Q&`&bz+#6#NFT*?Zv3k!hEnMBRfN47vcpR20yJAYT(5MQ@k;5Xv@+J zLjFd{X_il?74aOAMr~6XUh7sT4^yyLl%D89Io`m5=qK_pimk+af+T^EF>Y)Z{^#b# zt%%Bj9>JW!1Zx_1exoU~obfxHy6mBA{V6E)12gLp-3=21=O82wENQ}H@{=SO89z&c*S8Veq8`a3l@EQO zqaNR8IItz4^}>9d+Oj%YUQlb;;*C0!iC&8gaiDJ)bqg(92<>RbXiqFI3t#jqI%3Y( zPop=j=AyLA?pMYaqp0eHbDViOWV-5IUVwx+Fl6M54*?i+MadJHIRjiQoUe?v-1XdQ z5S305nVbg|sy~qPr2C6}q!v)8E%$i~p5_jGPA0%3*F%>XW6g)@4-z73pVcvWs$J2m zpLeW4!!31%k#VUG76V__S**9oC{-&P6=^fGM$2q<+1eC}Fa2EB3^s{ru^hI}e^KPM zMyj;bLtsRex^QMcgF)1U0biJ|ATXX`YuhzWMwP73e0U?P=>L|R?+13$8(PB23(4Js zy@KS0vvS~rk*^07Bd4}^gpc|e5%248Mei_y^mrD;zUYniPazU>1Dun%bVQ0T7DNXr zMq4Y09V_Dr1OQ$ni)BSyXJZ+D7 zXHh02bToWd;4AlF-G`mk23kD=$9B)}*I@kF9$WcOHc%d6BdemN(!^z0B3rvR>NPQ? z+vv#Qa~Ht|BiTdcN;g6;eb6!Jso)MFD3{sf{T;!fM^OwcEtoJI#ta?+R>|R;Ty2E% zjF8@wgWC=}Kkv52c@8Psigo4#G#E?T(;i}rq+t}E(I(gAekZX;HbTR5ukI>8n5}oC zXXTcy>tC{sG$yFf?bIqBAK3C^X3OAY^Too{qI_uZga0cK4Z$g?Zu$#Eg|UEusQ)t% z{l}Zjf5OrK?wkKJ?X3yvfi{Nz4Jp5|WTnOlT{4sc3cH*z8xY(06G;n&C;_R!EYP+m z2jl$iTz%_W=^)Lhd_8hWvN4&HPyPTchm-PGl-v~>rM$b>?aX;E&%3$1EB7{?uznxn z%yp0FSFh(SyaNB@T`|yVbS!n-K0P|_9dl=oE`7b?oisW)if(`g73bkt^_NHNR_|XU z=g?00`gZRHZm+0B(KvZ0?&(n<#j!sFvr|;G2;8qWg3u%P;M1+UL!9nj)q!}cd}jxK zdw=K$?NuLj?2#YzTCEw1SfLr#3`3x(MB2F(j!6BMK!{jXF%qs;!bIFpar}^=OYmYm z86RJ9cZl5SuR6emPB>yrO)xg5>VucBcrV3UxTgZcUu(pYr+Sa=vl>4ql{NQy4-T%M zlCPf>t}rpgAS15uevdwJR_*5_H?USp=RR?a>$gSk-+w;VuIhukt9186ppP=Lzy1L7 ztx(smiwEKL>hkjH7Y))GcUk`Y z5ECCi%1tZE!rM4TU=lk^UdvMlTfvxem>?j&r?OZ>W4w?APw@uZ8qL`fTtS zQtB<7SczI&5ZKELNH8DU6UNe1SFyvU%S#WTlf%`QC8Z+*k{IQx`J}f79r+Sj-x|4f<|Jux>{!M|pWYf+ z-ST5a#Kn+V{DNZ0224A_ddrj3nA#XfsiTE9S+P9jnY<}MtGSKvVl|Em)=o#A607CfVjjA9S%vhb@C~*a2EQP= zy%omjzEs5x58jMrb>4HOurbxT7SUM@$dcH_k6U7LsyzmU9Bx3>q_Ct|QX{Zxr4Fz@ zGJYP!*yY~eryK`JRpCpC84p3mL?Gk0Gh48K+R$+<|KOB+nBL`QDC%?)zHXgyxS2}o zf!(A9x9Wgcv%(sn!?7Ec!-?CcP%no4K?dJHyyT)*$AiuGoyt=pM`gqw%S^@k8>V0V z4i~0?c>K{$I?NY;_`hy_j6Q{m~KDzkiGK z_ffu;1bT+d;{6`SacCO z!z#1#uQP5`*%p&Urrk=&0`h1PBJxx*71yfl$|0Lt5_Lu$sO+F4>trJ6BS{J-of(R; znqrX@GUAyelkAOB;AqN)kur^1$g*t8&pGsyNZ|n42P$;s}e=Ef0&U zeA`jZs*E%l;3wd$oo^8Kh+#$+NzBNTi(70iEH)=Otim-ufx?&1Fe!w}-a_WL z3b9@#v&pt7wVF#bkr-YWhG|rhfwMABMZ<*Ku}@(4l8Aw|vSX#w9;23Ms1w zSC<+Ir!HNnF0m<+sQEdpqfFZn$+xA08nrn>k%Grb^0QdkgbOV;Kit2W`YwlfP5RRT2G3s4h?t5)!UZt~ ztK#FBL&P1pKsrye8S{&w@^ExelK;!LKh>=_q@VYF? z;_>~#$&OM13&!w@lx3P~g8~N3^wGM$Ybs$gFU+qlyxpp`?%oPWZNF-V;}NI47Q3^L z6zQ5TW`2EtX}l&7$2>xy4$xi;EXMN9^>l^O zpX}dt^G-p)6VSPIUolW9$svfNPfx=thP`;1S+wNs+PSh6QZ=X3FEu=#Ih!t_jC#tY z7t4@L1kbqL!4$7DY4QrHWPRfRvrE1hZcJR!wneIey(qiO(&qR5njE7~Vx5a{vafU= z)ya$}INqMlnsl?CHs*Gm@?JIPF$yE8pr2XE$;!z~-)=K?U$T3tT|t*z%Y~?_FuuG# zdxk5YL7D5##gr{wj@q_8USae@D&~NiU&5b$mcj$)ciL;Pm?1INBK8<9Uy##y@F;CU zG{5BquPJ2$`&r0uq3sHTD{+s!8^B47^RipsiHgpRoUp)5`1Om|oJQYZFd->&WM-2Y z+jMSmGg#v0-K{lm@K7En;FAw9nqm8(_94>4itl{!&h$c5Jhb(>aE;^WG5a0ho_P#k z=`>n+Y4`!6VFcFp<(fDGn0XZI%j$-p+V`Wfsdx5gviUanQCQKMLC02L-kZhqAFDJKEt24JM32 zX>A|&bwLR-xGzX@mrw_b>J0xDVriQ#YH{AYpBzPxW*}IViqyF8u~q zU?C~D8N<#3QCgHa! z%i?KtB+B&v;W5W8oy2USy=LKTj+&_Z`QpJr`GcqVwtDRmc6|RBE?NV#eo})g*6rN} zhVAR1l^#prL+5!{^P0NZ+RejdQ+Ik@^7pH{{xCL;z5Ef)do(8!08u9ieL2#1dVKMYKYZxBy98#CFs?lUx*#_eEO!>K!DVcH zdGN^HncO_w*;SJDV*_W|+&${EN7qQ1S1yi}H5b=0yu!PJ`dqxvn|pgs`A^1u$=l`! z7AEW-85?pZc4n>skM$;VkgurkG)2ecbYIlvN>b%UaLQareR0du>kXIMne04Rjh>ja zOJm_v=A~pE$}gH^TK6G5iT7xseUX#3keV|HJR9+g$u1o)wk^sTKGu+^WK4Dd6|PCC z*&kMT2?F_IS8|8B=Pgvkp`~)4nQ&T0-*6`YgSiY(GYn4))c1*2(ByIjf}HX8)B7rC z&d5F1D8EZT|BW`XU*~9w2)wL&5BLA(s{AwN`Cq`IT#a9vsG4Y>{48Y5F*r`NXsH?- zVTMpq8!(pQLZuRFNJ`bUqAX!QjVN;EgzPSiZEP^R9oBqXv+2Lf41bTiXwO@$_dEag z)4$-NHxpbc;(k6S`E9%V_Z7f<$NO$<=f@U!1BT{FA;w$gJM_RPC15g24TclHHNn= z%3))Msl?FP(v#6f=JB3R3(=~4{1-z9c(u5S4a?YsMm`I{<$RtS!4}}}Ls16B*~;RA zCFE^3T{I0u&U)AygIU#$7lBjVWRxt%JD|3mUGu4?1k3&FxUGkmjn>V`{dku=<;nM6H?3 z8xw;O<`w#tgfx@pCrNvj1x6M;bIoMn)ImU<%Z(~Dvg^o_X`D1>gDTAF1JlQ` z?Y0Rk=%+L12xR2Um(UM}Q!Uv+W%0yiatJP4)MXpxqnE?ceur3dpWVT$$C7W(Ad7OQ zW(07FjoY#!D~GG+S__T8FK&rdV8o2D$m<$v|3OeBckZrXV6vJB?+I0Q&55akuCrPQ zZU*OQXVhoj-{S`xTc(oCS}h)dA5qXgY;`LeY~fN~j3}d%Wj}YsHH!*FgWWVKtEo7% zHJCka&s(kt!Ix0uOwK~ysoe-RpANP#;|q6T$^GHRvO+{woF|P1&w_Kq=aoSqGzz;$ z*Wd$VhR9xrypy(YpJ6@06_07w6Ovvj^KcA}U4Pw$jA_~vwQAZkdkBBr8`%yn^BXnF zY|1lx{c2Y~DyMp-ZA=8M4nE-5zQ0V;O>J}Y+q0W4x)$_;wo<8D%n z!`fVX#C)T*rrWYPfxn@Q6qUT_)*!tiSediBO-cWahFdGUC+AFOSeqs;VqMXEvu z*%o*tngNJ+?;X}x>R4%u!~{AX)S}i#{yd>aw4uJZu8tysnfsX->l#F&^>#dTfy;r$ z9&&l4K^kS`n=Z?f{iVrgD@h2mp&`v~L{?|ix`67n;1n!!9Q9;ZT8{Z%tjs%KO;cRe zPUo=>|D{SI8*Zta^OK+@3{;6}Prl^Xo^!LgN89!4j#^fkSbG(fbc|}r9kfF?xK6Xn z1YQ@5h8GS>!!w45QHt_v&=*8WKMCyg^sG1>yC2jI6$OMH3*2k5pYYxNp2ruxMERnP zt>?dmG`|IjgqE?Y zfm?|c1z(LRCd0xBr_~~k6@@Vn{e_;CW=N{cxgOB7t*8bx)NVks2EHMQr1{_-@iJ4Yow z&jrCB7?wL1L^MwKQ<}W8nuXleT$a{lrIC+Lh^3X%lVS-Jj*O+ZeScuA=u{mU3<%Ru z?1Ta~3{lxdLZaLB{rnA*1cW#L6jcEUfR8x&{D2H-1!dw^=@(e4V zBXPJ#v7Vw?G}0~t&j@4v@@(6bhC0Wq;*N=}g9R&l+ltUp+C|&cLHD8B64iDaD#Ufm zzBugB@HF5v-1b26O3@fuv`ye?Q@;2{aG^N4zvx1n3|nzp+b3F$EEwVhHfn!wWrHgRcNDg+Ls6o&2!~fr|<5?3~C$xM40nq>h0pa?ejgP_Um+osTtap#sTgEz{+V!DVgg2c|zr&qy`*v|%k2qN4o$ zG~S$V&%H9mvmN_*yjnif&S_LWiH3GhJ<5yURu!%M^{oke1@N`vWL^&A({Dt^_*?zF zlEwE&e!1B;B=VjSvmW&#RI9p;59vL-zmfhqVSAUbyVBG~M#rW`BM9#;U-<(X5@k?g z1!baee)903$R-8_!>)ezvDF&ECABnUmq@;}jy$N;%haQ)b&?*%Pj@Zx<&(TSPsQ!- z_%e!bOqU&-@>_GE{lssw9He!Q4iIrZC?rGvemrxq=ZuF&VNVbL`14U6X|at+LC)@` zR8$!C=E++&j+(pty&FMQAxl0-G#pW(N>jQG1P2tvmz#rF&e3`|lwl z_vYYFF~1Qo=)yCVr!-;LzgT&I7&7|z9fN9h9n@0MDUi3~0_6bOhc@D2&^ z3duiUjQ;{H{ue#*zw_EcH6#7eEU^8|o4Z+g;kYqSw5Srw;B7BSV3Jyv$P(N)*#_vK z^_85Oc-QFw)3z4o&}w$QRS)*91nMOQ=(_P~ZMIbN`|4_ZI<*?Q@0jnHODEZYb7YNa z#+SIKx9tP({1fk!sZ{@be~5nfcU3c!&;~H>pIeMLx@HGdj_QX_a-&5s5M$~&{a`c# zA&Ak(q{ef>Gz5c^Ws>UyiFa*j#b4!CQU-ibzM|cGDhWsZV zPSM2}nveE~=5PtYB;8~Plz235H}`j{M)BvqI^wQGEc z9rbH|h#k#qFbKto=fbGP=fs$DGd|LTF%%-<=*%*scyqTgW;|&88`L-(y7Tth9HVaR zp}o`R$h{t3hYWj)%I-A!LZ{EALwwb@{TtF^4+X_7df_N(Eq?3Fxa#anAZ860o$rDoQyT;#i?`Kwurj4}BKysK7>nVQmatS5Nsshp{j zyS7G_fo*7u(Q+P%>ZN*aCp~9=tjao5cGcNm4 zx^?@S<p-aIyE;r_=AYe)b9h zzj^rv6QQ-}v0Cf7A|#5k>wLX}mH8FX52>q6R``I5aj(>*f3i+(F`6LcB&TwV1f zpOPb`4mv{k7WTW=>?1?FmVkn5!big+_SX>=c}=YQa&e+ez~sI1NEr5z9CTehje?9U zeQGJpCSAGIe8Q0$Z1}|?U+hS2PcEBSm6v21_B`XcXFU*4cyc40;{?Dg}W`~c$C^r1u0R%RqHCJ>{7(eSO$^7u3m~WQPS^$-(q&7a_2fFWJdGZdcs!8Yp93#wJGXC#+@-XFx|>~ zWg5SUiLzII8_j2bhj18wt_C_~^6>s+zj6K$qg)Pb`PYDVX=J7L+tMgt(x9w6zse)J zrWWHgUJmp%E@Gd$ZWQOvCOmDbvme4&D>*tpQvISkpoe!jph2$(V=}62#;K-r=px{4 zV=SM&(@pKFvW$W==2-~S-Tw&1LunP`!S#K40}R=1o4hYtUAAOR^O1p%&9v1;e~Mv!?1a_tMZAvG7he; zE(!g+ibYMAV|59+8DrA`A5jc3-gU&9%Ehp+qlG849RhUfZbL>lW#RoS2DMsm_Ux=T z|K|#Hv5ed&H*>KDzXXiopOce3I3(3%28T)wg51@M4yl?`judhBRFQ^Vxk)BpzD!Gdf#ou14?8X#gV$8aQC5b!&aX#wKA5qk_*wO!kHj9#S3 zfpfT#SU6nAV|8c)SSQA-8;;j_hf|h4AmqgK#I6X|Bi^JQUvhn%9ZFX#PLyfSQu$;$ zzM^i?+bX!Uuk9@9_E&+n1OxbcWwm-2^nejN=dF`W8^)>>#Cc$L@=1?vuQ#K}JjXsYEEOT{m5D-P)P}ys7UNH36m!HX{b7{zuY4R~4pfGV5Vi^-?R147 zD%l%2-?es1+bV6G4n$6GR4p(3ko&IXA+~(xQE|GL`XUzQacBze?)~!~HQF&6=utZ0 z$Wf?>HaxHaz7Vdtqw>KzA8y(;k}a|po=YGKx1k_^^zUDdNeGE>hyCRQSXcu*jL_YU zN!=4suP9`?J6XnmB6T|AChiP{Y{!9n6(*xTCBh?gJ`=4!L#e({8F5LQ^NHK@iL&LB zgD@%`@R`-CxQ8~aQh5hAwL^!2&`ZWwUt^g&CcMWa%{?u|%Q0S+=Zk`S=5!;nMj;)A zUkgmCf6>4`t~Sf4PcwYnqZbg3OF+Q)geEkt@yolApC*~;%L4b=P0^y0Dri{El=}4S z$X4s4+!}Hx*_v{nC%i<}C)#4{GV~O3b$(7WKQgmbWK*gp&bxjZMh%oA%7c;!x(UHc zJb*6c%(FyzY$UeZKe>)OnXJ6J#+#kL>6H@(rRUrJPT&TM*qJ(Zen2c1RTdSPih#F! zhNn89$nUneJz{GFdfXdLUFQ%+Dp(t{OZ5rb!Y)=Jk+Cg+kyn#$K#0-9B_~2J6CFQ) z1(JpSx*^=Z{P{OsfeXY>FUNrUD+Bd}BJlGUV)>t%g8pBcg8m;&Wk(?Kfx+?rP={4# zXB4Stq}8RQ<)@~n=q9G;4pa~n<(02#W|Wy4l$aV?SeP4F*wr1~;SrRXSeV$3Xs9OV zWaJsB+vFK#C#L0Fk3jzx>V*bA5$Nc!#SHLCaDciOczy_C>}F+a zO7CoDVrJ#&`nShmSM0V2BSt!Z(j+N{2qK1%?~(#uI1gQ1s>&W^0~xV~$nW z4pqV9;_`dmw}E=^?_$ry*6P1uvj2Kx3FG%^d_azjDv%??{GVSJHvTIB zZQ?5GU}py;Zpm5Mn*nKY?m&d}e?_5F)%1b9Xf%E>*l60e2)o*ydBme)*G+*;5h2RXO{)0P3jBG!L33uaJwzU(K(pv6~PPVzduR2|hw*i9w{(m4H zBS^uZ&rjFbkp|+v;LoK#iFk42d*MUii-&oRJm_hgMI7Ij!|4F79K)8we%~Y;)z64e zS$jZBbNXza<>?Hnzd=__%v}Z)E?tM3@C=^0c3OGpH?ILc;6K7CJHRW^0o;XM&? zRyJSjn0{#e%)dIN5KGml)+6Tt5Rk%+b&h7b*=OocxlFgC6=_Yeu5~|Rx0`VjhDk+} z<1I9`MFiDJFW4|F^V5yTKG8Gp1{v8H^iL1$d}T)KJxxi)uAvV7%^lcAWo61_;M?f+ zt*ei7zH!X4`WH_gd3aFWxuF$D(d1WGLYmrxhA3;SE)ls3ScyeKnCu_!>V(aj4|d;{ zr3d@%!lvC;Q^la)q%*jr_6ZQMqc}5=!j^g{!Y;_gLZ_z1mP1(2ofH+aMc@mO-w%0& zMcrLi=K@|Aj0dKfdi1zjUc8csnps7~J^oOr(crZ%-P>rt(vk^@obDhK%gz+COLyaF zOK@m(fV>GSpm|uvel^6QZJ`+Zq9q=64v>|~qAQ-QRn9AVlh7dTet}Jl$Bf8BlOeSX zRdEVg+lIQiT7;oB750LzS@a{VP{TS=prLli-EQdbR#XfrQuPc7PpO_wgy!O)Ji!_h z%o-Ied!{_J3E>-Q7Wy8R*O)${Vc7n6e#~E8k>#6Nd>OC{o&rDr7D4^1=l-n=Dj7Kg zfy@8pf`-Nj|AlQA|Fmq?fptIXim(x#Q$hn5A3z;;ub{UAm40w!;0p*xQPt~m6u1*4 zG~fRH;R!m96b>aS7IJE9-?nR4o6#^XzbT`CX){A=WdX)s+j*4Jw{yysmET<5g zhm~p#fBsf^D;F0ldkaO!zc%K=&KAJy z2(D)T$~~m&D=r$MjeX8>bk+VgEg0531O;L47sQCx5<0@n!Uiwkdzo^@5myP^w&}xH>73_@ODfWks~GrQLlMjj(6T=VkhF~X=S9fNiHaa$-%?#Z1=j=+S= zuh=Bar9-re^IBgu-N?L&pE2gF)wsS4Hk}wSgKhO1FhZhMJ$QNnak zc_Wg5E#j$$od&Rmk2X^SPW82|hAD%CQdfv%199y+R!Md+Y%xnNa!ceFR9YkOTTG2X z@degv0a@FP( zQGp(nd6$`yUEyu9VQY|1p^_;z5irnE5((Xij0zXIU3O6hr|mv*nf6@YKau^_`vx?U zVzk*ma1d%XK^Zsn6?b(_#C5Y>sgU1np+JAL$q#%lcx_5fq7N~y8$%Y1b@+qlZD)GRtqHiH64d1`M|6%gSI z7E)Ka;0tb#V2V7kP2N5ve8?RHqQI+D^S;>(^p{w&^T-`9T8M^17^E zj64Ug&h1ngxbO5^%8Q*oM^ZU3ix>(+wxqIv#20;@gRteOC|}HiWCLR4chOZ?sIl#j z?HWCs7ES&pYvD@XBAlD2DNS!N?o{H^RV<{m-)}D?NnIgZpCH&_k7h&2!m5!?4~$ha zLL0|~NL2^L;1mhwQu-$|4NgN=T`D#77(jGn_Ram-(H2Uz$; zf+hAb__g8npk=#_HZo1EbdbJvfPcy%j6v0c(TuA~CFWa#IpQ8DxrpD2g$oi(I2o2Z z24*~d>3T%gvGu;W0(7PE2QwGulFsU`yBy^a*R}SEcuz4PGa`L2Shn)X|0CKj$vi!l zaCDGyggSmFjrM}3;YC5#vSN>etg=m3CX&S4Axc2$Ts^+a@NfA#fKQutd*pd^(A_V@omWc_Wn z2hQwncEE}pKwi7qKc@PBPVuRUGcsVzXrYR)ti`QuI(D>YgTN!EudAs+5kX8H4W)0c zIAw{MVl1p@Hk~vb*I#_7n5AXW>4UVl4)eC&0I0WrZeAgG;bu@^)>w=-#R1~M{oE%( z<@`afh5m|!m6*!N-#^rxklo|Mz(ZxZ&B4|4VcoMwNXsBy(X2|3rvfBIt2!o5jEQrv zLw1MLY3@bD$B^%WBD~XC;wrIl$3tP7Ga~QLxD64h(~D$xN9m+3Eh~TMA+@A?zLmjI z$OvS($*mc z>-7O^ek3#vj<28l;F`DCy?7}nY;gV&6-Qpp;dX?e@leTJz3`e<%0*?O&k9$~VgWeC z_Ui4vn7u*k%x~Zav^W@jZEk{?&K;VrjDojuT6A9(_?togSE~qOT7HfJd3E8yiZcJJ z8A#S1STN?F)6hQ^$ln%WfR>FX+7Y_n57T6A3b3$HkU)*{tOQdR#4pkFEyP77VM4fa zF)bTL9&(VJtectZ;O8SUx)%V0c@7QlMyQSNfifr}Jxc}+MGq@Qil2{OuYA6*JNdQz z7Uu5F*?@*f!MBs_yWFd-K9{%I%aPAK|1Uzk+o_EZ9(4ue#Kov4D00}uS~1eMw_XOe z26zT~Ws1^Rh$bR~$k?m96>tz9%=e*8eOiHxdsA|*?Q;7+1~xE5egC=U=gHTn_#;&3_e5qQ+jz( z#pK^U8DYooTFAZK!MuY$$v%@;d#Mf91Ko0^ni3nW;{Y4nNn%=+D(z|A1>5cFT8s;)$qzErjML0 ziD7u7Hr$LASvu{+u9@x_)!~Z@iA6lGvb93@ox@E}w&Xc2)i=D=sh0f+Cvrt#$my5u zNC303wf!W;06T1)$Lm{&d0Y$R)1|S~WyRi7i~gVEJ_xzqMJD)m*o@XwEOICXt`la4cZ3VE78XZw0i9+>*DdZq@D`>yv7e({AvkT zkND$hT?3sR$7&DkeK`u(N14p@CQx#T*#3>0o^v-hT^IV<8ki~k{hDQ=f{o2MNPL zvoYAK@+7+xM*b3hZU-Nmf#%Wt(5PKm=5e#$TEJg!(OX`=TvDG=Tg2WG`EU|Ac*5tY z85?if*_GzFqJ~gBzz)m>lvTx(1B$UZ+(cZKO6+2Bo%rjvjn=Jgk(cRF6ll4EcW62w zIB7jGL}6x)r3O>_+lm-=Y`752QuDc8j|%+N(1)967Rg$7UWvkJG6uMzn_*^66b4*8 zB?j+c4Em#C{Kf`OH?n0qAeXHrx{4J}+xkpj826q~{uJ!Sp9c%>iNsxf+$vwQbbriw ziVukQ&@}iFkJP0kM*QY@SOY8Ws@i3L4^3Z%;3!$fj>B0^ZX+PgA6_;m`3_bu<*7QL zOZRT~u0FT}zGR$QwTrTi-0=wZXdM_w-WG>fwhZAoGj%2mDnDgKbYF(a=o{Fz-^*gj zwzOeIUv7)FSh489crAf{uB+vCZ;S5vy$Yt+fsU^*oAk1xygJ<=eG5BmUWczQfVVcx zAQy^X0uUL(p6C^S+L#7s!HM}|hC1}4ynle4i}drxpbCt(MN7^jC+l&R!+M=xb|n=X z1jf^Ouk_Xc9|v~A>R0)F8)zKkpO&Loh-m(PwZ1qf%wJnQY>+H*#vE8NEs3vT?}hFr z6cxV&Qqi{>kYkYUEsvNiVlfhZ=*&hcj<2^wA+xtF?0iN2RGh~5Z(jDwqHH?_EQL)! z63nv=^p9CAjFTguG~%8f$>GQYv4*SxiY!~i*;ix1?P+pn6s3MH0|SnU=3ORVK8nz} z6$#yIU7NL4`_Y{Bl02XZ7RIqTH#BItO&v$-W^XBo`_< zp;G;l+!qwLoy9y$h^PitL!U|q2HzHJ_k67`3tq0i2gx>cHzkFm$2W&qVDh|>T@Z*- z8wHeE9-zq-8AF!-x~s$f*t5rM;F5bByGh54r^&yPhggy z!rZr6i;^ia)kRBidKTcwqxnG7*JoIDr!?Y{$1{S7R)NY#4k^RKS6X2CER#1qPHoZS zNgXYiv-gACuEa9{Pg()P?0j5$$xQpyySA%fRpa^(9>=Q==fjIFVbM=F9Ky$dxln}? z2R}0&P)+o>emVfEceeQrvWBjB|8kIdz0E6bcDb_4*@yp&u{C2sa6yvG8ece%%-E~c z5L*$Q9ZqZ_1);e}P?>NK{hvNJ3_EQYjuP~ir#tzGx`U;+Pco%E#6dSS$Ou?1QiHOZ zUa3ZZ^!DggCSrpzryEF$k!(+`p3vldJ3W;2>pah|pU77#bbl_nd!o1ebDZ5Xnu^e# z3{mYzgp)o9Aof@d!ajp(M#d8Fg8N;6Vm)hbK`KL6Nzy|#$~TcA7`HT5cJip{bAUOS z3uh4Cv|Qf&V$rVLMOtpZF3?gkg4q`irJfIlQFRR0G=hsYT>AYrtbC72;EY_GyKN7v zE;J^7@d=gq5AHdZnJ=_`IU~)Gmf}u*;HMRD*qF%e-@$u-DFi$ljK&$DX4?er(mDV4 zdz63QousPUDK09Z`Pr}jROZ2QP`!o_gTr+&3m}3+&N0ToWXdGIF~Odp`=ztsKAgXY zxEKAcU&{FTJf0+Plf$J!W>3_6j{k&vuJfs<#lOz)15&9!E{5&c^!`>85g2G2M{1-p zfu2G!kkLv^+Z|^tZ7WxZwT2>`wwXK5$c-7hA-dNxaC#qapj1lhuOQWy<6hy>U@zLp{i>v0goz%WXZfJyM zAMcRmS{A?{94u@#r(Sga6JB##GIpf(C(KEmYBHlqV4p)T8=vpJ8yfL-S}_3RLQTi2 zE+I!C{5lx?OYr^WzKnY)aZ)NsfDs>fz7UP_>3i;YQcK-*4zbgh8(3b+Tgom5;)_}L zij@)AlIK2edojLXpN*)MXmCtss`*^-f%q;wrf}uXd#L!28(5NJmVOj@>Amj zvdBz39zgT8E8&DlkCft^UXevw9xGLOq9z_{a;nr#DeIUmB*`SPGJ;LYufmmDBd6c~Z?xdA z5prm}Ot}XfA@)EW{a1m>zv?{xD_ZbBdv@yfHvc~=x>tQl1-Osr=bs=mViAHux(SV- znm~fuDBFW_@`bagNmm$R#(hd&br zS%lna?|A!i^C_p#_j2a&ePj@OM&C;GzNo1w2szUebw_|!!>W~Bq=b(^OLr_1;37?%(##A z9QqVTl#IL`v(s%~0|Vz+8R>R@70%rCf(8>+;Bolb=5|toH%qQnyJD0H;lj36f&FF- zv%vwW^W=7uE3+{tR{!;xAX|f%`?f<<3qQ4-K?b!^8McJZm&K`-oG9J-tIVR0N)v9> z{aBjsKPjhsqU_1k?ujZzgwvyp;3OIg_9-xmJ4TqE<`xH-meDprmKKT9>?BQJ_c$=4 zjMxCytYKO3UqmSxF|O>r8NQupgg$=6j<$YTZlq-vBOF9{)e1{MgD+H9X&HZ7BELnJ zD)MD({Ai*5$spJF&E#uBOCx_s%Q?Z|#xuboK2JgdNp_GN>mOv6H}Ftj3C_15fk*W6 zQ@LssLl6rPe{u%XKQemMFSN>X5k(eG3>`eO2By+`tF7K7B!hjx!dnk)yJlSR10b2O z2~BPBdu&x5k6P<_Aq3zO_HpDFn zm7Q;ii%GQB6o=RAyOL1UHO{0M8NTY_mJt1l&frMH7X;blR$2Z^D5yG9sg6FBDs+M+ z0hVhb^~MveK6(`s!kkYZt#CVp7HNWEt@Um)yU(WX70HKUY-{esU-SNNJ5ZAE6FNyi z|0@&zKZxo7HhTWK>-?ABtD)<%sDbn+1#7BN90hK8kANt^1a%7oG^Iods$EDbphQ}< zK)g|1QY}$W`*`84_XD=)zV@gTu|;*TWZLz0Sk&T`@>O)hPg28ly-Bt#IdV2{IS=6A z@q_=C(EsxlHz57S4v&|K+=M5NL(a{Rcl)#-&OG$K%yXLD5$q0nYncAVQ+9L{dMk{^ zL|8%~ZuYD)D1nW*m$anFlWw$N%u$kRCw2g-iri@h4N+D?dej@mwEFNgO*?I#-A}T& z`j{rp{;-VALQ7;U#ehw{+}H-?apebor9J#I-EkS7E@$)*rI(2Eg|V45YwoYF?N6q-{yTyLb+>FoKRhs zx~U5_mvk~*TTmNK(Va!L7;yCIocCK5tt};4p-zA$3c$EM%1K#z7s{cmSPeB?LNvCOf8`?3{m|5el48Wx=_l*sG13tpH0Nx;9;ROU zRxz`t)G=g})nwWgNEf6ix%fGhE;~$JZG6&t*Hz%HIDVFJUA0SOyU>EMSEOTLiUz^k zC@Y~I7~Bi<7$GTPNdt4apBM86LtrR3@b)Yu;$fm_>Qk{x>NAb7q8I<$tc`cMXcOkq z=tq#^b!8Bk$SYia^abWU^EVrj9YaFKR$Z6{EW^DM8xMT9Z^mi^n$J1|oFwi$(KPDe zKF)h_X&!ni(>43<-=?*Aya_Y&y1&Qq!+e84G4ArPYMgiLMbtB&Xh_S)x%C$5o~uA! z)ISR^g^3JbT~!XiS`I2O;jyKK!dI6ipD7tIT(q*{w^tTrjSd>98OR8^`1SL%DUMr1 zoty*%29FrQC84%B%?K&EpagbmC9S3#$NlcEJ9y`nDk;d!u(-pfxKAEwX6NZHKgaP1 zYB$t_?F>eqRsQr2>Uw z_(OydVzS-~dc-l>{X`EmXAFX|Rdv9?J-mu_z(Aqxv^0Ze@0{dC$IX3^)}7NO##x~+ z9M3C6>Mb5#EE{I2d$azj^w@8$olxgF)9&oV`R*{O@bEZuYX)Ni|2j$bO%CT)Xd-hQ zwM1mrelZiLpY+Xh)RzFFoN=AYS10)wSREU_e&dln{ z-QKeQ4Br0Rtp2Za%>Rd_n5v@xSMZj?<>`xC}e-2KbVN?1otV0?Gf8uQuiI;twFnF0IOGq z?peO7GocyicU|yBF~GmL;iO|tCQBMo$&+-Fe;;HxPY*S*AkpOSf(S8XHh=UVc##ea zUQaRg{R~7zJCOi?eunC3;h-z&h)|?vFybC5n!%)VF{ASnIgJ@v|1lCxIw-{#tI?R2 zR$KlKZ;d!&&ucn3VFOuYA0z&9T-#_62%0Il%L~~x-znb z^P#1s5Ls!ytkHobY|s>fX`IhDv$zgD*P2LuysS8~D;>;?tiXW96Yq(SMdt#r2AZN7nB( zY5D1c_=t}FcIrtKLhQ>N&i0f&^^xW4qbG2fc#aFXFkfGhFLpNdT4{4F9?z|eK1<@! zYJFJPZP6h}oM)-VgkP@H$qGr1{U!-8lV*r59HgUqeo))HmDcBxVN^SQ=c^=M!;7bF-Vp_D#LR%hU=jFqOXEPi{` zviQDBaVvs_Og+?TFK!#hKwRuun0>tT>GTS9P6N9v|F;E+*IB6uxeN$-&$(;!s^}B; z-_SSmBHt%-G-WN+WHD_Vnn#XuC_+S%<)Mjv>q8!SuJBCStZuSZ+@D>+QWF3)fS95C z+4FTz3MpP=#?w>~0EN%lq3aHC!_fBisQ)?c_lB#r=EUDTW&A4A0 zp*joPiR%T|ptP>8Q(b|7+UP1$b@(sFIc)BKX0JdjS9dPjmnRYt;BuzfPeLlK zOxIUiI;BB2mqZ4H`HIu3HYo0!^@?RLpD@l=q5OG-o-U6*{X?odL|e`4%dJ+x3l>+0 zYqVRBTTQwwuj445KL)KJ!f!aB^(lXK=xFbT78!!PWeYf7)Al$ZQgMZVpOIi{)`?jQ6EGt zN1Fli^1-fQ_AW6%$y~nM{){i_1&A>$M_X2zsV>$$W{(fgty9e0&XaK%Wx9|P?(RQ@ zeG?yL81E?C<W zZN5#>k7@jMrYLPHOIeH1CpOsju9{rH0jI4h`qTq_mOfmrj9}zlOFZ7zYZvFJnE758=N6laV5R<(K#1Kyo z1+WD$nO^oJbwf~l;1+i3LhT5J7^fJYLms*@D>Q~0??Wbi*eH?7ovb#<531*sBqUvH z+U9r0YMiyeOG4U{^oDtp!AW)(StJi2q)@BV3s*IOD-`=*=AY#uTmJ(1^>p@7EIoXFwrc%;%KzWnF5|D26z! z{AaY}HS?db4Dx-hI3$OpXH?G=cY?vO+%f#1#0cmsw{|TTqcs z$L7$Vd%UAhzcx=P+Mg68NA>=MlLqmJuZxP@X2f28{~GD@+LyiN#*x2$(bHArR(-uT znfv3!VgHYf0N^cm@>CR$o9t9P4L#kW7TQA!Pz27Z)<^kRut0`|$oqMS&?>DUdp73?Z9UCZntcGFK-dt^CpAZwmX=VV5T+Ypb^d`CxT@_i6szTlgx ztHgj-1grdsMplBJC`(f}U?U7w`@!%?6;+hmt2Bm_otM`4-fLydBDZ8CKnE9@vHAfX zUoP+WRBN7IyU=;_AFV#%$PL^L-qDLfLgOq&dAd2pPISue{D)>YPcvn&qPdp07-1eU zzJDfttKVorH42n3Q|=R@#KfayWiZSYWe}uptFi1wI=ahv%D{2W04pkz=4cbEtRpWX zD8LmDRE(7XP!T*dRX`z0B$_?w?IiTG$iAuQgQD*ULx_(FGl2j^*?Pb)?RU*2QuMbo zEq&RT8!jCtp>^bPXv!Co^65#Q-Q9T?rJPHk$4=06@MVVAqn~Rm-r(mRmHh48Umucd zs|mYU8p8A|L;auv@pA^4^Y&>0!1Cqe;Qp%&JNaQCa%Cgj=*fBm6^-mmiT`Q zOy(xZDh>*vh0Z~Mi}?sD4HcdDgX5sO9gr%=&=!$lJ&E$BG24a1fkA)DXi_k|fB8do zfL6u4CU!t~`74Ke=ia@{;fk>ynq<)>f_A2MBjx5jg4-*-&yS3@lJS?O*9Tl&(@{Hdun>V2VjoU!p4XJ!u z`sV`b;DAv378}(tQWIx4Ijx6h3rnBHRgtieSnJw{eu?Qv?bCJqTCvm2)7kh_@>RL# zE%Fr9705W0o4C+8Jeu%tkrhY1f)6VZJX9p%e1RJw#{M$Pv5(N0_;s~wQLeYYb@ned&te6Ox{l{(K2M7ESVja1Hb3MN5H12SzFVU&LuBa|JH>666&HxE@r?=J7)GS zR<2g=X8&^*sZ{l!fml`_x?SVMwrA~;s5Hjz(pO`mSQ%pxGHa2=r!SB>=IeIu>A=c# z{=5HQXq0iHFD2-WqV8lzQdX zpKGm1w&DoY#gCFXaYu!X#7~p8CZu^?wQ)Uhs+>J)#PBJe#i}`uWi7Ph0;s#YAz5Jw zw~`e9sp-JY!2B>YhrZ0WjIK*AfMrTq0Qy6cjwymsTqkw_Pg9>xqdU!Lpb?z0#YoJ^ zmSnyN*RguGR$M-9oW0O`yzbsk*yHGP8Q-bGzsI|JiQKmLCN~M z8*#-Cx#tXmK@Ref1SrpIQOnx39dW4^ZlAs~Z@hb&J9NHS#1U;BPiUoAwAd!c9Mj2$ z24#}W2~M5TEN!HZrU{wJ)beG8>6LyKM^9yK@zbEC3o|AQ@u=;&qX>f8xF-JY%P^=s zs8pS7oUnskDO7)cj-gy6M#OT*+zct6a5@B{(0$cU44XEFrn39Q^6T6;+xR{Rn>kr9 zQrP5C&;*oe71IpJJo7gZJ)_U>PCxolSD^3)lF2{qW?^i^sZ!ZVK`FVcQ-G%3vW?@F zb7r)Kt4A4b%}sUAO|?dOLlj*$<3+4c_y7@Goq)wK>Kl%#zS!GZDT>Lnd5SL?sxSJ* zk1i@+wA z`hcof6#rthes>nC!?`F;*Xq!oamK}gk;Q=c^O7PB8pMJK`+Q;+Rf-2^gboUJk(7(| z9ekdg0;2FXcZ%jhp(Iz=Q?;l}MNBG0p|tEo-?GGWiQnSn=wexO!QI+@!OdKAul+J5 z<^6L+ip!0SLq7M4)|vT()00}~*wCtQ|btkyWthyh~dUKeakz#nBpKn!2FunJ_|0?lFez^B?l?~^x~Im2#$gf9FHTua z1}8l|>iSq5U>Ui}f#UQ);$8!wiJM-YCKP)2#6*@>h$>*IGFdW_8OlqBK@ED7?wf@mzih}MD&(oPbMp8oa&M-Vn;!CTRO(PmSZvNd#Vsw&m>#UVlWeC z^B%U}?{rm;HZ6pDMJJ=pif6JxrhB0~MqAI_t`;X!eY~#$r=As2XuY>Exy0Cr?AUUQvr1tQBLDCBVIjO5f1?rZ~# zk(mUxN>!87(fn2tE8~r-6^nDKvi7O& zTN<-k_2v?lG+Pr4odH%FecI+yo}bR-h7pR3=LZiKW-1BS{9S6Fm-WaCRRj>rU)k8u{Jt9)P_v57J2?b z@}gr5rVKk=Ep8KcoyK^rFth^g(-DA41`fi|Nl!Mow2BglypUaG%16C zd-UKWwM_DMf(5=s?}UXyn72%-pv{0e;WbPrq6J9Curr6|pid9sc2b@~nGZ!(_gW}R zd>4#2(+JK4?j)oUQiDsG4IDG%v5xOp7}h_6`JjAN-GmoJ-4NfDjb@t4%hh%3kM$sOK}rVT+G%cLU3MeygHY~yq>H5 zXF*6%U(^`%5(K2pjha}Yh;&dL)d&@mR?T3%_i`4C09IJ%CJ_~ESs{CN3lFp<cEHYvvZxsME}pi^r~`wE zR(Zgs-l?`OOui2RwdVOqNP`MB5%Y(uCqdyuh6XYj&SY`ji&KT8yGk_s0Q+i;aM?5- zdy2{P*c_p3bO^!G;}kI3o#7$-plZ7pE(%o1`*$eB4({rt=cR}Juz3?$kt1+a8 z;q2}fG$OYb{8u2zQ0y)_IOhEnw(C5*RB+CwEeoqwZ4=qSdrSrEIj{YN4rBUoUm1NO zT&9H=c$!s`QXI^CiGQG>?ity42j7-hG3nCYnYDF*aF4$Nl0N*J-rsr?EW|$y)?eTQ z2a_^9HEZiWraH$4_S?5}E;s8VTaYVVQ1ERD?Yf^Vzlix;@9=<_kjoh4!-VxF7(uQK zLIv(V^FP@Z0kLFbm}Hg-?lE-@eHS*8U?e%r$|a%#0Z_k6BX9S^=%5-5q} zh~z!E>VCuTe}W~#+u@A;g;>DwQ@6*!D#Iinq(E1cnMcoR1$4ay6ygxOKhZ`71sEw> zJGoa|#@cGF!myuz3IL(n2d_ac)Ull+s~^G3uRU|o7<8(8p)66!W)zR&>`*4XQ~t9e zj%HD$_=pu3GpiS_FA5d=Zqhlee^l6$tTkf<{yurrMT0T<#@W>k^xkDdjEaprF($T6A#m{3NEFeK?V9UJASIzNF-3;$ZW2DJ1C4 z+60`Xih-PF4DJWLECu}lbSQ&f05tU2g!ZBzDX~SZQWz#fXiB^3r+P9xv;FrroTv=! zni^qGP0eLX5hx{6EmPGNBl^OfAvTVBS!e)CxDIej#izrN?OhdSUs4TwE}r8B55D6> zMRdgCkm#~y!4AsJI09fVghHl;r!B0#0|cnSpHf#TRU3(KQ9_m;c|^YAxJFPg6do+d zcV~ChQN{yZX~k1)4WmyRmPYW3LupYAiXhiQ93_Y~8QAfM5UJu^lIgNpU%JWgHN7ls zmq36DlRpz@a(1!d-W}9$xJmzN(}{k~nv}n`>bdFY2191lQLW$AV2&x8P!Ei+Liqi$XVbQ7&w{*$& zBHO=doIpiDJSm~dY3K#HiD;6*m2T)nhf=X>PTeJhI;iIu&I7GXoptfm;HrW%yy~^2(-j6zk z@fCK+fx#(HG}>f7O`gwf~?U2yt7x2NojM1imx}>oPJI*zX!^ugOE9eJm@Nz$D(bQ5 z9agonHaTb_)4q&ACr{}2`YDuuMA#_TpUF$Q1-FNdsn__Yh78DTE8KH7(ym_t#UbWjpCo-UXKEbpHc=OFO?@3(pH!ps znXe3cF}&h+q6u|mp8X#GIec3BaUoO)dI=O-DSMp6xE$Rd;av z>pJ!+$cC^ag+|Z`Xl2P87>7($#y&tSGI4A3E=kCo1kz*@ld*Zmo40nuLs63hgt!+< zVP&d&^)!*nR$fDWM&@16<>xA3~$dOR_D`4x?e5|#72UnM4tjLE?IvvDb>|Jd#9OqP* zw6YtaPywLJwr9UwZ?y@R(Rb#;RlZfC=aw07;)8ivdEwqd-83jsbjXO|+k`(AOkI%$ z`bnubTn#iAx58rKeIF*#Eo^Hs z2p9*oIW;U{LhUdprOLtN9Z-OjpM<XPqNMAh;5WRA{JA@-VUBE2Asuc$Qh;|2))eC{&v8byr*cob)JHUV#1(swddDYOX=T{0x@Ug9EETtB>jv5?5pBU- zAjHz08TgDn1JYD+_u!mt4_{-Vax!}|+rM=tIOFS+88_5+ z^BXQVNIs;5GoH#GCaDX2XJ({vcktV_nT~cbD*}l`xvf_UM0`+bSCmZR3Vc~HW$Znz zKKC$gOupRqOr$s!35_HL79h|Tt4(;)_|jm{=pnSAGSoNW^=%o{7I!-IiDJK!r$IF5 zGzPts^}}ne$!=@OSr@HcP(GsmjNV8jERE?3m~{agTr3{!bi&#myZuVobHV`XSrbx} z(*=o!s~OV~+v~^ZOQ>PDIdx|Q#>53NLqVK^RF?wY{9aTOfuYowXr}uE-YUnqGujt6 z7+YO;F$pqnpiDx?XVhCvlSL)L$+axX%5Ju7mlU1OIeo$M>-YJbWbf?JT8k?ug9p43 zmOn_j4iUPF;GD|d)>)#=(tH9-{jB-5rlzPRX%xa^22>@9?Fqzz+g?jh7<${~xLtB? z)@bnFv$wXYROVA4-KdwG)U5$RE$nG&1{o+zHlcU7|8r3vOV&e$uM3&`RRUB%UY;45}9WNEqN@ph8b!( zQ8Oi5($^`zUBinEFBIcIO{SV6`D#$`G>|2ajnV2}f{!g|xiq#?%R{=x@pO*sxa?B| ztR)sIlDLqA$_P?m!5m7!CJ8rxlw6&LhC?&O6Hh%BPL)nvLMoFZKEH=}a%mqheg~bj zLK46)Jm&G7QoXPqBy?rX!!2!R%=t#^mT-3bsxfkTP5b=WinPF{>TdrR?ymvzeln=b zh`IWl)VgA`Aj#y0_9S;qZg4GZlIc)JNUaPvQG^(xui-MI;A$iJ$g0Nr_Wc17S#S^YWjl3PusxQ!)wU8b8 zFDF#aeJM!o$?`DADxMHNAZEJ~37%z9K|H`EELfXxd1kk~1D^+fVfB^vE8gX{gus(q zP8#n>$2_-_?mAGc;a!1_r%;Q5A2Rl`D|Ws8XM%2#K&mA6>S3ZSgN+PlDTfZgC=(ls zm&A@kk;cmfW89r0B}hsr6~eFYifW50>0>}L`!=SQWrUPCV>cIK&lak8qFzeUO^%DK zb;G1evX6LifZX+YX)KcE8#6f0K%rmfZCvGrDbX}1=o|~8K3Rr?$7h&k1ziysH@RgY z{wk6x@9k^JpF6y3O+|Vy=g#O%A7KZ_!Z*svG$;09pWmGH?5PE+@IJ+K63A3G zRxQj3C%h%n3+a83X?IpT9C|j9f%VX-U^n`S?1AX(xE>Rd2=n1Z;Z)gMjS=KX0e`3S z7wBro{K8hVEJ`ZaJaVVTROdCtB#>bNW}5@N=l7*#o*|`}5%^--4HcpKSh-7)JenNy zz(_n1cZ_*HlPkY|<1wAGFAe^ejgC#2M~>K80Zsz*A97m>&%{gwf-fO!IGXHtLFPaB z-&53Z_*)T-ofB9e3q0E0{0fPG;tkNTN)22HXZaVdDl#DeP*32mFbMm<{8nWN|B0FI zf2hYh*oDNS3i$x%CkPjxlN-XM-~l}-islg7!sKjDFkQ~(EOz?zTHAvpR5~}5r~}D} zx4z^}Rg52#tlI~!tHl+ron`xltoF9AATRpDATcI!tCII9rBskRRh8cTef438rEkUHMhEA+zg*XY08C@c<&hLhWA^8_Fv^SZM)W~Il7h@#hDRC z;D_T-kWj22P#@^WwO4$^dx9mjFu=&H?b^FyH@T(Ly$Bt!!KMOW$9bv6YG|h&2M^YU zCGxhRi*YJ(LBW(c8<*WZ+Pz2mS#CJ})k@Uo4>!wACtr&wu2dnN-KP`r83?6%l_42R z3D%P12Dd6P;xiy_Xjq=(8^QS3tyzaReeH-TW18P$VF-W!G`Ph>d-x4eY8ZLYmgp_Z zN$pPinOpkuoSq_cpCbmxXSF`rphklW;_gG+x-7lZ>m?x$PFGc&f+o51$}<}B8zzt4 z>4S$Hz4fx|ian>^e7yJc2lsNsE(y&Gmn1~KG}7n2?}h6gDi5h+Z?gyZpALhVB1tKl zyx+4x3bXPMGD}i|@INOM4O5vJ>)#(s4g~!uzHm&n4vs91I=ssj8Ux)V`sV!QOCp|9 z_)YS~Fs67!5t8AeXr`cQlns=!>|H7kiQC2;Z*ghB+|?dPB@U>Ja>Z)GbHAgb_$sMgr~G)JhY{!TEY52na@|#S?S|HmaH06E?59!Gbui(%>6w`R-#h5uMX! z0J{rT_9=QD=D~G4vDNy`P7OnhnumO|Y1EcXWM(=djE1uos--9OP5}>zC!E4gpZ6C( zuD8)|P^CaSANdHayg=YFqVm{k>Z;)4g$6&;Fwb16N#(cZ>?-D|Q$Ew6KV~-!=U7Av zc*Pk>`6Q(P`qiA!!dlj>Yxr#hrp(uX0^y1cbC&^-pjoU5SN^QxRI$TJKUQT^OdMFO zPA2$MH*IjCoTeJVPa3DO`**Oi)^2xR+ATF(WBu+l?`1+>>tS=-VaII8yrzTK*C{e_ zDK)^Mg-2V;&pKI<6S?Nj)K%_Bc+ONA_WB@s;!}K%9rZqZA28~b$32&j`F*+oi`%dm zm(`mzf;~jxBz~Y%;XJ4j-}z{o22D(mZ_g%+g5vo1aLV+J7s4Zz$Rv2aRq=+G7Y??8rDt!e1iy& z)&NN*U#B+|7pcEFX(?*S{}x+~sr_k;458jCT!EMH0>8L)kbk^!4L-?NjJOB(piv7C zo;6lt^LKi^A}3RkE{r$mxtW+{b_}M3LMM<>S)i0Wx*}mC5~~QY5?whdTa5-ih)t`h zerXv`DOtuC2}T6FBT{|Ot#W)CV!A9B_w>Zqn^H`TlVwXLnBLQ9_T)9iVlN%@X^G)- zmP+cbr6;F!2gQm)O=+EcU{cTlHh>V(2mh1uE%#RkaF$v!s##wN?hzfce2EP! z^VPf7wJtvzpICd}rF&j)RJ`(rvVjng(NWe)8b0JPO|bK*)vOO2Y;VeV19|}&w>9@ zA2~5HcZe}|+`+L`Ww2!1ll&Eh6tMw%{O3e{Gmm9d*vm`+lhy}p0JRQtg1&kr){q8o zLcN6|^;}wkg0ifpVwusKmkQ^k9L*NHP-IFY;N5Ccd@9_FZ|75USR#U-rg&}%h9+UO zqJNk#C`giY?8LjC5LY*DcR_PR!90NpCku;h)jY;Y5l+yID$8tEr}DajdRla|C!JZ9jS7ZNR?01x z(29C1wdrL=YOxVlG-&JGxru#`LvRr*x#&9t!iYKezI~KPJOY0uOXC!x^tjzoC!+N3 z{nNF^nX*)eZU>pfhV}$EAxl#9Qv@T9k_3ldr>eURyt9vm3j@@h<(CKp9~)y4yxE9;sUsj8c(7knL%j`1o#`5%Ch&^Sez!sOEPdI&6 zVDw&BqsIW}LMCTJ0HjFlnA&Wa9t9CkDK zXj`8X!ztT=v=f|BhhEyJey-fUg*2Mzmw1dvGsk1nDft>e$HrwSAlXa1HpdRnYj;#G zFAKPvbfbS-by>00KuvT{tAU}ryQZXM^I6aXWk~r!SM*_jo%ySU?%sRWqRO$7btT1h z66E7j5S)>9RjUTgF2?NIVycAJas+~Dw$;R!gXH%!)4&kKZlqnk=?tkW#kscq+yboW z+rDQal~@?2_heHhcafFu&RM;HvEow^*-ICyJ%;E*c@nCl&L(6RdZ}o1F*QZG!QBbI>Sga6MhY zJtASBj*zP)0>ULKMME%=^Q|Ms0&OsoOrGh&Ur|9MWn9}GUE7^opMeEm;Hx)FpK6=$ z_{v~P*=6*BN?ENw4Q@|+L;X1+8)Zi~fzB>%!h`h^bpruB>*Bp-oO;obx^UH&dKbO$ z(q8}M=W`~0+uJFDUkz7WMhiv@aBe0B&dqec8?N7iGXK8YB2rQFKhh#~_4G%i`C8~g zR9HFmLt$7gFG|3fNKAY3ApNaHc+`WwP0I8r-mo7i+OD%hrK3eXflK-y4xi>e$|6?A{B10 zD#AtKv}EPe(^Pt9YGbX4`+_lK8F{KDoVv&%CLAH+g@SXJvA)2b~P z>boypUaQ}6JuuS^2rJSMnz?|-^5S+$xt5PJ^Nq8*`Z&O7bQv`9F3GXQpNe)XQkz^p z^tlEZ8Mr6Sz70+qeI0ZhLc0vns#%y2L@V)bnd_D~!9l`QSKA-FOWT~a)${p8 z+TfUfuJ7Qp31=TU6nIiOcQdZCB3(X$(~<*+*oXDli+H*V(s*JYkt(*HH9Gn}#lFCK`}qFL#aAdF*HX&p9s~sLs?VmvZ?e*GDVXv}phS9WATfZe zCv0Slh59;TF(m5tX|l&tGKmJv5lLF(RIK0?3xFJeW?;XT3&8UX36MatEl}Tbs72&} zRjy4%<~CwS_wcN{yU50+!K1t@+oH+QjGY{erwlNSF7Gm3Fz{lq%(l5Jko+t0+W{vW z<|v)p!~=_#ZPFLCcZ-EBZAY91b2W`SDFK>@N6ZUZq4(xZgDWbsp98!@^srNCj!sou zbnOcjsP4M#a7!8s;T4|YR;^`{MfNy4Y3+m%yOw^u`?}l3!@pdh;-r}iuu}i*!pyg; zUX=Ybu;z8O+89#^3%8YlQg7~Sa=H?=@poZtL4hx}B8}Uq>*&^Qwp7?8S>UhWWNLZf zStvJnd5Lh7mye_o=WBZvN25s|7>tY73Bj-_x>b32R&1Sh^7j=AQ_eI-&RY(<@U<61(X_-G^BC@j6ZrN%T3o%&$Ta80FN_$+ds*mg z4Bl+7KLj8820g-KM9N!88(EefeLyXEr}f1E>FQgJV$ad{#7w~3$WkRnHjdjU+s z@8GxI1|5oJe8gu!J%r%-m&`dt~ z8U?WpmRwOb!9-7yLjq=~7tZ;VEK{yu_+COu9zvF1zI#(71z8uuskuKv@8l5fYXv^L zz_!sKI77Te=J{%r7KM8lznuCrZJbCZGE5c3daD@b-nI3whMy8#5*`N_wP*az8S%T} z|67FDqaeLV1zDMHL1a&04E9t-G35tRR#@>0S!ziIbWm8B<@&uQ3n`AOrTBYxqb{{P3i5k_Xu+7pGy6q}2>-lt{55ZSh?$Q8V533IZ8e z)AAPOU+%Rt@$JMZu%|Jx!Q{_3Rv!@LvA30H^aZ1fEvRDXhrTq~?Qo|&hqP@s<1Nj2 z8NbE7CeK`Zi$&fz?gpc^Qmz&-d^DO?5pe7c*EQm_?vHsBL0kP%DNWEs*D;k|7>z#d z=wqqTDLXzMTjeXI#Z>8j6+|1g9`jA;{$BUbP`~!C$T;TqJ}@HE1NcSouVn0mjR4km zM&hP+_6~}U`rrHiudm-;6-z~6G7~SWDjVBs6G?=Gx;aUIK^PBaUs4kAs7XX+*cG0V2~ddK#KcXI~0Ehk(PZ!Zia~Iclre z2g#qn6e9aNJp#Fo^D}-u&h633g_}c=9-Xm9f>Q5G=Ms%#t!YK|Y8A!ErF1KkdgYRG zbsS*^;3fhFrc!yg?pG3=+e_?P0JAiqq10yFZXCTivnlCRM+ti6LDZoXquQo2jizLd z$k^;*WS#Njw8XjsO~>XjDmG7MD!iZ^^^e6G73Sb+XJj}>`yq0;R78T!A(O6{K|+&M zbHzqGL?4?>Z9GO9H(xKQ)tJOpWDG8XT|luZD@RHf>uNSB3_55Ov=ljCQy_Xx7enuH ze;Kc5A>a+&L|lYO-A0mCY=yMqA~cJmS&6XKVsA`_m+*Z8kF+99<614pv$yTe{4}-3 z1b~yqt4#IQ$kj@ev6tR?MtCvcQNwIbUA z!;4kuj~H{_U;^a5I`?#33lH9fZunudyVD4_>d>guC)K*~adU_y9lS)kavh4CuDmeY zPrQ{x{~!WMV~8;VXqc0m9En$TUyy}@--hr%)xkcriO%#D*}tEYO{jn2HgE1wkqY_B zSQsPyWpzO;-I=z_GLKG?N-d)EN80tTXOKp78?&olk*?c&WYc?SNzb!kCwU?u{Bv6- z2avMfUY=jMMFBWWj|+7|d%Xi0Fy#+BA6P~_U9#pU^&_=Kh%|+LwELk9@e0_w4B|by zaTIFF@wz1%=FV?9Ajc$H>yV1Dodg-LD6w-it5zgtvTlzMgKb3#R7iCcy33OlRFoKAEQIE;yRz}PME$62;E1Bs8Wu2 z$3`~C&1~Vn9L^PdZ z33{h&m3EtM%nU{*tO?j|CYgN}V~4?UnTTf_20QLrwjNr&!BZ8{PR4s&9+`9s`~Bpn zS~`O1I=$5UDEK}u&x}b3yWtwd8W=CKr1(8#zjDNWA^O#Z#DVane2c990<_UwzuRa< zS9=E|%YWlj$cP=5?iNH3`Y=~wSz9+_HZ8WuCX6Q96NnX!iS?4<#hzCx;baUM8pWjW zvb3rn98pIwDy1oMkx-9%I?LIIhmrKg7Vnm}Cml~Ll8BKaNiEQG)B{F9Eikghh`on+ zDL%j$&fi80)(!VdX3rZFEd8qsA)NQ<`4s)1i>B33S;BQuw>+VM(+vPt`H6QJyj@l;B#6*A|Sezu|o?d)gbzUWi2?e>*W zToiD2)QPw&zook6cb8t$CH{hz!)qy@4sh5G3|M^kBB#VHCS)$< zfjGZ}yA4_-2}yHFFfu&`Rb<5xvTet~?^JCdr#yO7xo~13pi9kTui2t#cUN%}BDPZJ zBr{xQ?OOPCx=tQ1ml=l~j5=H? zXt+&1;);Q`jM)zp_OP2u13X+cV`M%rN*IE;O%5#ava-;MAJAkg-8%zu8&3FIuOm~E z6RoI_;MDz;z0ue&HD%%4T@T-whr@q!s3-(ow@f_L(#(B<8?X!6F^4BLDc(jlf_kfzXp@Daq@}O$vpcE`Z zOprA1o(s;W8=33^s4ob%XEhnqnBI${#&-0~;~x8B+Ylh>uLe_zym~D$dzkueR^k)qj?i{>RJ4!OO`P$oF!Z(0Na!A$oZ9jk4)$AW$k@ zsFk0+q*4_|yWUfVko^Ac)hMNGpt+1R#KgsN=QE&Yts2Nw4g zf#f>$@4|ta(=M^M#a&}v5NDcrv|*=8I)iaNSrgTEUQ+BzZ49t{i`qeTJ?4r`6v}UO z0d*>2(eM)y1=Qlq3|O$R>XDqc*qn&L>*oL@`Y0(`S2B3nrbH&A?&sF2#pN)P%r)~Z zo*2}!U2Y%KG~!lYKNO2}#)M~Y8P3#=H;;`SWCPw1RYvB-jaxGO+7D@}tU>Qxf zwOXQKeTsepe_;H1Eu%YJy?4zGYfC1A!5`jNW0WZb$8&gqCXS{e`89LelT1Pwuk^T8 zkrE#XR0<|?U5zeyLKX)uBY(a3<1xnbO$FBG{qcgv- zbcA@3bg-F81b;J2{c|>=lsJx?DNfRC#8GMr5&6An$%;~Hb^8a4BFPTW$l|9ttpZjp z=|Vh-qbV9`&UFO}s@oEP`1`(2bmVpw0dGFTr&Zg`ftxB_%F7qr!c9#|=qwx-ptY z#J~DLx`a^pWv$+V%3ss&YhC-^-rQ$>IuTMsj42=)a2ju@hO$jrIO=T1hmDimUr}X0 z!f#mL@j2wu_y|{1Z3I3?JDid2Iqu5?qb0%7*x88J(@3>T1=;{pANA%OQ~SB1$(KCc z-uH+Gq0vkDB-zOVX&Yk5Ybqnd5 z6{OV1e&TJ`i%i*?w5$C|LIWO+5DO4mz`OqH*QZi5c2-jYXynC!ClT=co&^B7)&2h? z13=A-KV$&d`bGEu2`D-kFi$u%GzdO$(>;**zq0p0^YHyZ200S?_ET0&Nr+xbP8_&X z|JPz&pmmGibc>XLC;GSl{C?#5e*0YfZ!uXRIVo{5MWtu5;*Sx&6#!0k|2cru-S-0- zE8h zKm$d8EgbEE8_UE^EsTT=42c7XPc_ z`L2vjD!__^0DI?~$@p>9_}*ds5&gNf@&D|FQM-dM3}B#%6|l|U_C@_TYJ6V&%)x*XiFW>LwkUonE*6Q zzuqTahCiYSTU$GP%e!GCt7mEjbh`e`w()ofbczuVi2(0WE#_Z26ModS##e^*kI>(T zfS8Msf#ZMW(;uS-;O3Q70a1m49Z2&7@;}X=;{PM+Uk}B1>~EF+b4NVRaQg$g#&=Ze zkGS8v^?#Y4$0-hf;t{;~Bi=8!{(mJreB2w4)93wUp?vvAmj7*W{**Q6C!Dv&e`n9{ z2KbLN=-=!2O>gFL(wm=vD4PE}17FHlHU&C$p3zPo5#?#ere@54V%Y>A7_#I zQM|@iW2al;9OU?hJdTaDgRR2SG{xSSx&Get}{Ko$T z|NTzkB1KdE%B{{_`wo%Vlq*JJ(4pCo>E|AOS7)hr*k=&{`2PqGfje&+o?LU+wvS%=vh)_D{~E(EpqB&*tiJQ0-65Stm4}a^s|D!>Voy|XKl52jW`5Wx_2K{yU2iy19>-ZD@r0!qf|8F1U p \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..8a0b282a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..9ab64ea7 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'auth0-api-java' +include 'core' From df82b6f307f8f6cdf1962cf46b91f33a08c62761 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Fri, 8 Jan 2016 11:57:38 -0300 Subject: [PATCH 03/89] Add lock-core v1.13.0 "as is" from Lock.Android --- core/build.gradle | 5 + .../main/java/com/auth0/api/APIClient.java | 368 +++++++++++ .../com/auth0/api/APIClientException.java | 90 +++ .../com/auth0/api/AuthenticatedAPIClient.java | 116 ++++ .../com/auth0/api/AuthorizableRequest.java | 40 ++ .../java/com/auth0/api/BaseAPIClient.java | 75 +++ .../java/com/auth0/api/ParameterBuilder.java | 166 +++++ .../com/auth0/api/ParameterizableRequest.java | 50 ++ core/src/main/java/com/auth0/api/Request.java | 37 ++ .../auth0/api/RequestBodyBuildException.java | 12 + .../AuthenticationAPIClient.java | 469 ++++++++++++++ .../authentication/AuthenticationRequest.java | 112 ++++ .../api/authentication/DelegationRequest.java | 79 +++ .../api/authentication/SignUpRequest.java | 105 ++++ .../api/callback/AuthenticationCallback.java | 19 + .../com/auth0/api/callback/BaseCallback.java | 14 + .../java/com/auth0/api/callback/Callback.java | 14 + .../api/callback/RefreshIdTokenCallback.java | 39 ++ .../api/internal/ApplicationInfoRequest.java | 105 ++++ .../com/auth0/api/internal/BaseRequest.java | 168 +++++ .../api/internal/JsonRequestBodyBuilder.java | 47 ++ .../auth0/api/internal/RequestFactory.java | 95 +++ .../com/auth0/api/internal/SimpleRequest.java | 99 +++ .../com/auth0/api/internal/VoidRequest.java | 84 +++ .../main/java/com/auth0/core/Application.java | 183 ++++++ core/src/main/java/com/auth0/core/Auth0.java | 105 ++++ .../main/java/com/auth0/core/Connection.java | 133 ++++ .../java/com/auth0/core/DatabaseUser.java | 59 ++ .../main/java/com/auth0/core/Strategies.java | 106 ++++ .../main/java/com/auth0/core/Strategy.java | 44 ++ core/src/main/java/com/auth0/core/Token.java | 78 +++ .../java/com/auth0/core/UserIdentity.java | 144 +++++ .../main/java/com/auth0/core/UserProfile.java | 172 +++++ .../main/java/com/auth0/util/CheckHelper.java | 37 ++ .../com/auth0/api/ParameterBuilderTest.java | 139 +++++ .../AuthenticationAPIClientTest.java | 589 ++++++++++++++++++ .../auth0/api/internal/BaseRequestTest.java | 124 ++++ .../java/com/auth0/core/ApplicationTest.java | 97 +++ .../test/java/com/auth0/core/Auth0Test.java | 116 ++++ .../java/com/auth0/core/ConnectionTest.java | 135 ++++ .../java/com/auth0/core/StrategiesTest.java | 27 + .../java/com/auth0/core/UserProfileTest.java | 128 ++++ .../auth0/util/APIClientExceptionMatcher.java | 81 +++ .../com/auth0/util/AuthenticationAPI.java | 174 ++++++ .../util/AuthenticationCallbackMatcher.java | 79 +++ .../java/com/auth0/util/CallbackMatcher.java | 87 +++ .../util/MockAuthenticationCallback.java | 76 +++ .../java/com/auth0/util/MockBaseCallback.java | 63 ++ .../util/MockRefreshIdTokenCallback.java | 36 ++ 49 files changed, 5420 insertions(+) create mode 100644 core/src/main/java/com/auth0/api/APIClient.java create mode 100644 core/src/main/java/com/auth0/api/APIClientException.java create mode 100644 core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java create mode 100644 core/src/main/java/com/auth0/api/AuthorizableRequest.java create mode 100644 core/src/main/java/com/auth0/api/BaseAPIClient.java create mode 100644 core/src/main/java/com/auth0/api/ParameterBuilder.java create mode 100644 core/src/main/java/com/auth0/api/ParameterizableRequest.java create mode 100644 core/src/main/java/com/auth0/api/Request.java create mode 100644 core/src/main/java/com/auth0/api/RequestBodyBuildException.java create mode 100644 core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java create mode 100644 core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java create mode 100644 core/src/main/java/com/auth0/api/authentication/DelegationRequest.java create mode 100644 core/src/main/java/com/auth0/api/authentication/SignUpRequest.java create mode 100644 core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java create mode 100644 core/src/main/java/com/auth0/api/callback/BaseCallback.java create mode 100644 core/src/main/java/com/auth0/api/callback/Callback.java create mode 100644 core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java create mode 100644 core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java create mode 100644 core/src/main/java/com/auth0/api/internal/BaseRequest.java create mode 100644 core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java create mode 100644 core/src/main/java/com/auth0/api/internal/RequestFactory.java create mode 100644 core/src/main/java/com/auth0/api/internal/SimpleRequest.java create mode 100644 core/src/main/java/com/auth0/api/internal/VoidRequest.java create mode 100644 core/src/main/java/com/auth0/core/Application.java create mode 100644 core/src/main/java/com/auth0/core/Auth0.java create mode 100644 core/src/main/java/com/auth0/core/Connection.java create mode 100644 core/src/main/java/com/auth0/core/DatabaseUser.java create mode 100644 core/src/main/java/com/auth0/core/Strategies.java create mode 100644 core/src/main/java/com/auth0/core/Strategy.java create mode 100644 core/src/main/java/com/auth0/core/Token.java create mode 100644 core/src/main/java/com/auth0/core/UserIdentity.java create mode 100644 core/src/main/java/com/auth0/core/UserProfile.java create mode 100644 core/src/main/java/com/auth0/util/CheckHelper.java create mode 100644 core/src/test/java/com/auth0/api/ParameterBuilderTest.java create mode 100644 core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java create mode 100644 core/src/test/java/com/auth0/api/internal/BaseRequestTest.java create mode 100644 core/src/test/java/com/auth0/core/ApplicationTest.java create mode 100644 core/src/test/java/com/auth0/core/Auth0Test.java create mode 100644 core/src/test/java/com/auth0/core/ConnectionTest.java create mode 100644 core/src/test/java/com/auth0/core/StrategiesTest.java create mode 100644 core/src/test/java/com/auth0/core/UserProfileTest.java create mode 100644 core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java create mode 100644 core/src/test/java/com/auth0/util/AuthenticationAPI.java create mode 100644 core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java create mode 100644 core/src/test/java/com/auth0/util/CallbackMatcher.java create mode 100644 core/src/test/java/com/auth0/util/MockAuthenticationCallback.java create mode 100644 core/src/test/java/com/auth0/util/MockBaseCallback.java create mode 100644 core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java diff --git a/core/build.gradle b/core/build.gradle index b9f81c07..821b426d 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -1,5 +1,10 @@ apply plugin: 'java' dependencies { + compile 'com.squareup.okhttp:okhttp:2.5.0' + compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1' + compile 'com.fasterxml.jackson.core:jackson-core:2.4.1' + compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.1' + testCompile 'junit:junit:4.12' } diff --git a/core/src/main/java/com/auth0/api/APIClient.java b/core/src/main/java/com/auth0/api/APIClient.java new file mode 100644 index 00000000..14ee3a62 --- /dev/null +++ b/core/src/main/java/com/auth0/api/APIClient.java @@ -0,0 +1,368 @@ +package com.auth0.api; + +import com.auth0.api.authentication.AuthenticationAPIClient; +import com.auth0.api.callback.AuthenticationCallback; +import com.auth0.api.callback.BaseCallback; +import com.auth0.api.callback.RefreshIdTokenCallback; +import com.auth0.core.Application; +import com.auth0.core.Auth0; +import com.auth0.core.Connection; +import com.auth0.core.DatabaseUser; +import com.auth0.core.Strategy; +import com.auth0.core.UserProfile; + +import java.util.HashMap; +import java.util.Map; + +/** + * API client for Auth0 Authentication API. + * @see Auth API docs + * @deprecated Use {@link AuthenticationAPIClient} + */ +@Deprecated +@SuppressWarnings("all") +public class APIClient extends BaseAPIClient { + + private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; + + private Application application; + private AuthenticationAPIClient newClient; + + /** + * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). + * @param clientID Your application clientID. + * @param baseURL Auth0's auth API endpoint + * @param configurationURL Auth0's enpoint where App info can be retrieved. + * @param tenantName Name of the tenant. Can be null + */ + public APIClient(String clientID, String baseURL, String configurationURL, String tenantName) { + super(clientID, baseURL, configurationURL, tenantName); + this.newClient = new AuthenticationAPIClient(new Auth0(clientID, baseURL, configurationURL)); + } + + /** + * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). + * @param clientID Your application clientID. + * @param baseURL Auth0's auth API endpoint + * @param configurationURL Auth0's enpoint where App info can be retrieved. + */ + public APIClient(String clientID, String baseURL, String configurationURL) { + this(clientID, baseURL, configurationURL, null); + } + + /** + * Creates a new API client using clientID and tenant name. + * @param clientID Your application clientID. + * @param tenantName Name of the tenant. + * @deprecated since 1.7.0, instead build using clientID and baseURL + */ + public APIClient(String clientID, String tenantName) { + super(clientID, tenantName); + this.newClient = new AuthenticationAPIClient(new Auth0(clientID, getBaseURL())); + } + + /** + * Fetch application information from {@link #getConfigurationURL()} + * @param callback called with the application info on success or with the failure reason. + */ + public void fetchApplicationInfo(final BaseCallback callback) { + newClient.fetchApplicationInfo() + .start(new BaseCallback() { + @Override + public void onSuccess(Application payload) { + callback.onSuccess(payload); + application = payload; + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } + + /** + * Performs a Database connection login with username/email and password. + * @param username email or username required to login. By default it should be an email + * @param password user's password + * @param parameters additional parameters sent to the API like 'scope' + * @param callback called with User's profile and tokens or failure reason + */ + public void login(final String username, String password, Map parameters, final AuthenticationCallback callback) { + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .setClientId(getClientID()) + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + + newClient + .login(username, password) + .addParameters(request) + .start(callback); + } + + /** + * Performs a Social connection login using Identity Provider (IdP) credentials. + * @param connectionName name of the social connection + * @param accessToken accessToken from the IdP. + * @param parameters additional parameters sent to the API like 'scope' + * @param callback called with User's profile and tokens or failure reason + */ + public void socialLogin(final String connectionName, String accessToken, Map parameters, final AuthenticationCallback callback) { + Map params = parameters != null ? new HashMap<>(parameters) : new HashMap(); + if (params.containsKey("access_token")) { + params.put("main_access_token", params.remove("access_token")); + } + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .addAll(params) + .asDictionary(); + + newClient + .loginWithOAuthAccessToken(accessToken, connectionName) + .addParameters(request) + .start(callback); + } + + /** + * Performs a SMS connection login with a phone number and verification code. + * @param phoneNumber number where the verificationCode was received. + * @param verificationCode received by SMS. + * @param parameters additional parameters sent to the API like 'scope' + * @param callback called with User's profile and tokens or failure reason + */ + public void smsLogin(String phoneNumber, String verificationCode, Map parameters, final AuthenticationCallback callback) { + newClient.loginWithPhoneNumber(phoneNumber, verificationCode) + .addParameters(parameters) + .start(callback); + } + + /** + * Performs an Email connection login with an email and verification code. + * @param email where the user received the verificationCode + * @param verificationCode sent by email + * @param parameters to be sent for authentication in the request, useful to add extra values to Auth0 or override defaults + * @param callback called with user's profile and tokens, or failure reason + */ + public void emailLogin(String email, String verificationCode, Map parameters, final AuthenticationCallback callback) { + newClient.loginWithEmail(email, verificationCode) + .addParameters(parameters) + .start(callback); + } + + /** + * Creates and logs in a new User using a Database connection. + * @param email new user email + * @param username new user username + * @param password new user password + * @param parameters additional parameters additional parameters sent to the API like 'scope' + * @param callback called with User's profile and tokens or failure reason + */ + public void signUp(final String email, final String username, final String password, final Map parameters, final AuthenticationCallback callback) { + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + newClient.signUp(email, password, username) + .addSignUpParameters(request) + .addAuthenticationParameters(request) + .start(callback); + } + + /** + * Creates and logs in a new User using a Database connection. + * @param email new user email + * @param password new user password + * @param parameters additional parameters additional parameters sent to the API like 'scope' + * @param callback called with User's profile and tokens or failure reason + */ + public void signUp(final String email, final String password, final Map parameters, final AuthenticationCallback callback) { + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + newClient.signUp(email, password) + .addSignUpParameters(request) + .addAuthenticationParameters(parameters) + .start(callback); + } + + /** + * Creates a new user using a Database connection + * @param email new user email + * @param username new user username + * @param password new user password + * @param parameters additional parameters additional parameters sent to the API like 'scope' + * @param callback callback that will notify if the user was successfully created or not. + */ + public void createUser(final String email, final String username, final String password, final Map parameters, final BaseCallback callback) { + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + newClient.createUser(email, password, username) + .addParameters(request) + .start(new BaseCallback() { + @Override + public void onSuccess(DatabaseUser payload) { + callback.onSuccess(null); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } + + /** + * Creates a new user using a Database connection + * @param email new user email + * @param password new user password + * @param parameters additional parameters additional parameters sent to the API like 'scope' + * @param callback callback that will notify if the user was successfully created or not. + */ + public void createUser(final String email, final String password, final Map parameters, final BaseCallback callback) { + Map request = com.auth0.api.ParameterBuilder.newBuilder() + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + newClient.createUser(email, password) + .addParameters(request) + .start(new BaseCallback() { + @Override + public void onSuccess(DatabaseUser payload) { + callback.onSuccess(null); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } + + /** + * Request a change for the user's password using a Database connection. + * @param email user's email + * @param newPassword new password for the user + * @param parameters additional parameters additional parameters sent to the API like 'scope' + * @param callback callback that will notify if the user password request was sent or not. + */ + public void changePassword(final String email, String newPassword, Map parameters, BaseCallback callback) { + Map request = ParameterBuilder.newBuilder() + .setConnection(getDBConnectionName()) + .addAll(parameters) + .asDictionary(); + newClient.changePassword(email, newPassword) + .addParameters(request) + .start(callback); + } + + /** + * Fetches the user's profile with a valid 'id_token' + * @param idToken a JWT token associated to the user. + * @param callback called with the user's profile on success or with the failure reason + */ + public void fetchUserProfile(String idToken, final BaseCallback callback) { + newClient.tokenInfo(idToken) + .start(callback); + } + + /** + * Obtains a new id_token from Auth0 using another valid id_token + * @param idToken user's id_token + * @param parameters delegation api parameters + * @param callback called with new token in success or with the failure reason on error + */ + public void fetchIdTokenWithIdToken(String idToken, Map parameters, final RefreshIdTokenCallback callback) { + newClient.delegationWithIdToken(idToken) + .addParameters(parameters) + .start(callback); + } + + /** + * Obtains a new id_token from Auth0 using a refresh_token obtained on login when the scope has 'offline_access' + * @param refreshToken user's refresh token + * @param parameters delegation api parameters + * @param callback called with new token in success or with the failure reason on error + */ + public void fetchIdTokenWithRefreshToken(String refreshToken, Map parameters, final RefreshIdTokenCallback callback) { + newClient.delegationWithRefreshToken(refreshToken) + .addParameters(parameters) + .start(callback); + } + + /** + * Calls Auth0 delegation API to perform a delegated authentication, e.g. fetch Firebase or AWS tokens to call their API. + * The response of this API call will return a different response based on 'api_type' parameters, that's why the callback only returns a {@link Map}. + * @param parameters delegation api parameters + * @param callback called with delegation api response in success or with the failure reason on error. + */ + public void fetchDelegationToken(Map parameters, final BaseCallback> callback) { + newClient.delegation() + .addParameters(parameters) + .start(callback); + } + + /** + * Remove an account from another accounts identities. + * @param userId Id of the user account to remove, e.g.: if its a facebook account it will be 'facebook|fb_user_id'. + * @param accessToken Access token of the account that owns the account to unlink + * @param callback to call on either success or failure. + */ + public void unlinkAccount(String userId, String accessToken, final BaseCallback callback) { + newClient.unlink(userId, accessToken) + .start(callback); + } + + /** + * Start passwordless authentication flow calling "/passwordless/start" API. + * @param parameters sent to API to start the flow + * @param callback to call on either success or failure + */ + public void startPasswordless(Map parameters, final BaseCallback callback) { + newClient.passwordless() + .addParameters(parameters) + .start(callback); + } + + /** + * Request a verification code to login to be sent via SMS + * @param phoneNumber where the code is sent + * @param callback to call on either success or failure + */ + public void requestSMSVerificationCode(String phoneNumber, final BaseCallback callback) { + newClient.passwordlessWithSMS(phoneNumber, false) + .start(callback); + } + + /** + * Request a verification code to login to be sent via email + * @param email where the code is sent + * @param callback to call on either success or failure + */ + public void requestEmailVerificationCode(String email, final BaseCallback callback) { + newClient.passwordlessWithEmail(email, false) + .start(callback); + } + + /** + * Starts passwordless authentication with SMS, this will send a One Time Password to the user's phone via SMS + * @param phoneNumber to where the SMS one time password will be sent + * @param callback to call on either success or failure + * @deprecated in favor of generic {@link #startPasswordless(Map, BaseCallback)} or more specific ones {@link #requestSMSVerificationCode(String, BaseCallback)} and {@link #requestEmailVerificationCode(String, BaseCallback)} + */ + public void startPasswordless(String phoneNumber, final BaseCallback callback) { + requestSMSVerificationCode(phoneNumber, callback); + } + + private String getDBConnectionName() { + if (this.application == null || this.application.getDatabaseStrategy() == null) { + return DEFAULT_DB_CONNECTION; + } + Strategy strategy = this.application.getDatabaseStrategy(); + Connection db = strategy.getConnections().get(0); + return db.getName(); + } + +} diff --git a/core/src/main/java/com/auth0/api/APIClientException.java b/core/src/main/java/com/auth0/api/APIClientException.java new file mode 100644 index 00000000..991c057f --- /dev/null +++ b/core/src/main/java/com/auth0/api/APIClientException.java @@ -0,0 +1,90 @@ +/* + * APIClientException.java + * + * Copyright (c) 2014 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +import java.util.HashMap; +import java.util.Map; + +/** + * Internal exception raised when a request to the API fails + */ +public class APIClientException extends RuntimeException { + + private int statusCode; + + private Map responseError; + + /** + * Creates a new instance of the exception + * @param detailMessage error message + * @param throwable the cause of the exception + */ + public APIClientException(String detailMessage, Throwable throwable) { + super(detailMessage, throwable); + this.statusCode = -1; + this.responseError = new HashMap(); + } + + /** + * Creates a new instance of the exception + * @param detailMessage error message + * @param statusCode status code returned by the server + * @param responseError payload of the error returned by the server + */ + public APIClientException(String detailMessage, int statusCode, Map responseError) { + super(detailMessage); + this.statusCode = statusCode; + this.responseError = responseError != null ? responseError : new HashMap(); + } + + /** + * Creates a new instance of the exception + * @param detailMessage error message + * @param throwable the cause of the exception + * @param statusCode status code returned by the server + * @param responseError payload of the error returned by the server + */ + public APIClientException(String detailMessage, Throwable throwable, int statusCode, Map responseError) { + super(detailMessage, throwable); + this.statusCode = statusCode; + this.responseError = responseError != null ? responseError : new HashMap(); + } + + /** + * Returns the server error response payload + * @return payload of the error response or null. + */ + public Map getResponseError() { + return responseError; + } + + /** + * Returns the status code returned by the server + * @return HTTP status code + */ + public int getStatusCode() { + return statusCode; + } +} diff --git a/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java b/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java new file mode 100644 index 00000000..8a00ebfb --- /dev/null +++ b/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java @@ -0,0 +1,116 @@ +/* + * AuthenticatedAPIClient.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.auth0.api.callback.BaseCallback; +import com.auth0.api.internal.RequestFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; + +import java.util.Map; + +/** + * API client for Auth0 API v2. + * @see API v2 docs + * @deprecated To request a SMS message for passwordless use {@link com.auth0.api.authentication.AuthenticationAPIClient} + */ +@Deprecated +@SuppressWarnings("all") +public class AuthenticatedAPIClient extends BaseAPIClient { + + private static final String TAG = AuthenticatedAPIClient.class.getName(); + + private String jwt; + private OkHttpClient newClient = new OkHttpClient(); + + /** + * Creates a new API client instance providing API and Configuration Urls different than the default. (Useful for on premise deploys). + * @param clientID Your application clientID. + * @param baseURL Auth0's API endpoint + * @param configurationURL Auth0's enpoint where App info can be retrieved. + * @param tenantName Name of the tenant. Can be null + */ + public AuthenticatedAPIClient(String clientID, String baseURL, String configurationURL, String tenantName) { + super(clientID, baseURL, configurationURL, tenantName); + } + + /** + * Creates a new API client instance providing API and Configuration Urls different than the default. (Useful for on premise deploys). + * @param clientID Your application clientID. + * @param baseURL Auth0's API endpoint + * @param configurationURL Auth0's endpoint where App info can be retrieved. + */ + public AuthenticatedAPIClient(String clientID, String baseURL, String configurationURL) { + super(clientID, baseURL, configurationURL); + } + + /** + * Creates a new API client using clientID and tenant name. + * @param clientID Your application clientID. + * @param tenantName Name of the tenant. + */ + public AuthenticatedAPIClient(String clientID, String tenantName) { + super(clientID, tenantName); + } + + /** + * Adds the header 'Authorization' with a given JWT token. + * @param jwt a valid JWT token + */ + public void setJWT(String jwt) { + this.jwt = jwt; + } + + /** + * Creates a user and request a SMS code using a configured SMS connection + * @param phoneNumber phone number that will receive the SMS code. + * @param callback callback when the SMS is sent or with the failure reason. + * @deprecated Use passwordless endpoints from {@link APIClient} + */ + public void requestSmsCode(String phoneNumber, final BaseCallback callback) { + HttpUrl url = HttpUrl.parse(getBaseURL()).newBuilder() + .addPathSegment("api") + .addPathSegment("v2") + .addPathSegment("users") + .build(); + Map params = ParameterBuilder.newBuilder() + .clearAll() + .setConnection("sms") + .set("email_verified", false) + .set("phone_number", phoneNumber) + .asDictionary(); + + Log.v(TAG, "Requesting SMS code for phone " + phoneNumber); + + RequestFactory.POST(url, newClient, new Handler(Looper.getMainLooper()), new ObjectMapper(), jwt) + .addParameters(params) + .start(callback); + } +} diff --git a/core/src/main/java/com/auth0/api/AuthorizableRequest.java b/core/src/main/java/com/auth0/api/AuthorizableRequest.java new file mode 100644 index 00000000..e0af82ff --- /dev/null +++ b/core/src/main/java/com/auth0/api/AuthorizableRequest.java @@ -0,0 +1,40 @@ +/* + * AuthorizedRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +/** + * Interface for a Auth0 request that need Authorization using a JWT + * @param + */ +public interface AuthorizableRequest extends ParameterizableRequest { + + /** + * Set the JWT used in 'Authorization' header value + * @param jwt token to send to the API + * @return itself + */ + com.auth0.api.AuthorizableRequest setBearer(String jwt); + +} diff --git a/core/src/main/java/com/auth0/api/BaseAPIClient.java b/core/src/main/java/com/auth0/api/BaseAPIClient.java new file mode 100644 index 00000000..53767bcd --- /dev/null +++ b/core/src/main/java/com/auth0/api/BaseAPIClient.java @@ -0,0 +1,75 @@ +/* + * BaseAPIClient.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +import android.net.Uri; + +import com.auth0.api.internal.RequestFactory; + +@Deprecated +abstract class BaseAPIClient { + + public static final String BASE_URL_FORMAT = "https://%s.auth0.com"; + public static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; + public static final String AUTH0_EU_CDN_URL = "https://cdn.eu.auth0.com"; + + private final String clientID; + private final String configurationURL; + private final String baseURL; + + public BaseAPIClient(String clientID, String baseURL, String configurationURL, String tenantName) { + this.clientID = clientID; + this.configurationURL = Uri.parse(configurationURL).buildUpon() + .appendPath("client") + .appendPath(this.clientID + ".js") + .build().toString(); + this.baseURL = baseURL; + } + + public BaseAPIClient(String clientID, String baseURL, String configurationURL) { + this(clientID, baseURL, configurationURL, null); + } + + @Deprecated + public BaseAPIClient(String clientID, String tenantName) { + this(clientID, String.format(BASE_URL_FORMAT, tenantName), AUTH0_US_CDN_URL, tenantName); + } + + public String getClientID() { + return clientID; + } + + public String getBaseURL() { + return baseURL; + } + + public String getConfigurationURL() { + return configurationURL; + } + + public void setClientInfo(String clientInfo) { + RequestFactory.setClientInfo(clientInfo); + } +} diff --git a/core/src/main/java/com/auth0/api/ParameterBuilder.java b/core/src/main/java/com/auth0/api/ParameterBuilder.java new file mode 100644 index 00000000..cec16a0e --- /dev/null +++ b/core/src/main/java/com/auth0/api/ParameterBuilder.java @@ -0,0 +1,166 @@ +package com.auth0.api; + +import android.os.Build; + +import java.util.HashMap; +import java.util.Map; + +import static com.auth0.util.CheckHelper.checkArgument; + +/** + * Builder class for Auth API parameters. + */ +public class ParameterBuilder { + + public static final String SCOPE_OPENID = "openid"; + public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; + public static final String ACCESS_TOKEN = "access_token"; + public static final String CONNECTION = "connection"; + + public static final String GRANT_TYPE_PASSWORD = "password"; + public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + + private Map parameters; + + /** + * Creates a new builder + */ + public ParameterBuilder() { + this.parameters = new HashMap<>(); + setScope(SCOPE_OFFLINE_ACCESS); + } + + /** + * Creates a new builder with default parameters + * @param parameters default parameters + */ + public ParameterBuilder(Map parameters) { + checkArgument(parameters != null, "Must provide non-null parameters"); + this.parameters = new HashMap<>(parameters); + } + + /** + * Sets the 'client_id' parameter + * @param clientId clientID + * @return itself + */ + public com.auth0.api.ParameterBuilder setClientId(String clientId) { + return set("client_id", clientId); + } + + /** + * Sets the 'grant_type' parameter + * @param grantType grant type + * @return itself + */ + public com.auth0.api.ParameterBuilder setGrantType(String grantType) { + return set("grant_type", grantType); + } + + /** + * Sets the 'connection' parameter + * @param connection name of the connection + * @return itself + */ + public com.auth0.api.ParameterBuilder setConnection(String connection) { + return set(CONNECTION, connection); + } + + /** + * Sets the 'scope' parameter. If the scope includes 'offline_access', it will set the 'device' parameter. + * @param scope a scope value + * @return itself + */ + public com.auth0.api.ParameterBuilder setScope(String scope) { + if (scope.contains("offline_access")) { + setDevice(Build.MODEL); + } else { + setDevice(null); + } + return set("scope", scope); + } + + /** + * Sets the 'device' parameter + * @param device a device name + * @return itself + */ + public com.auth0.api.ParameterBuilder setDevice(String device) { + return set("device", device); + } + + /** + * Sets the 'access_token' parameter + * @param accessToken a access token + * @return itself + */ + public com.auth0.api.ParameterBuilder setAccessToken(String accessToken) { + return set(ACCESS_TOKEN, accessToken); + } + + /** + * Sets a parameter + * @param key parameter name + * @param value parameter value + * @return itself + */ + public com.auth0.api.ParameterBuilder set(String key, Object value) { + this.parameters.put(key, value); + return this; + } + + /** + * Adds all parameter from a map + * @param parameters map with parameters to add + * @return itself + */ + public com.auth0.api.ParameterBuilder addAll(Map parameters) { + if (parameters != null) { + this.parameters.putAll(parameters); + } + return this; + } + + /** + * Clears all existing parameters + * @return itself + */ + public com.auth0.api.ParameterBuilder clearAll() { + parameters.clear(); + return this; + } + + /** + * Create a {@link Map} with all the parameters + * @return a new map with the parameters + */ + public Map asDictionary() { + return new HashMap<>(this.parameters); + } + + /** + * Creates a new instance of the builder with default values + * @return a new builder + */ + public static com.auth0.api.ParameterBuilder newBuilder() { + return new com.auth0.api.ParameterBuilder(); + } + + /** + * Creates a new instance of the builder without any default values + * @return a new builder + */ + public static com.auth0.api.ParameterBuilder newEmptyBuilder() { + return new com.auth0.api.ParameterBuilder(new HashMap()); + } + + /** + * Creates a new instance of the builder with parameters. + * @param parameters default parameters + * @return a new builder + */ + public static com.auth0.api.ParameterBuilder newBuilder(Map parameters) { + return new com.auth0.api.ParameterBuilder(parameters); + } + +} diff --git a/core/src/main/java/com/auth0/api/ParameterizableRequest.java b/core/src/main/java/com/auth0/api/ParameterizableRequest.java new file mode 100644 index 00000000..9e3880ab --- /dev/null +++ b/core/src/main/java/com/auth0/api/ParameterizableRequest.java @@ -0,0 +1,50 @@ +/* + * Parameterizable.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +import java.util.Map; + +/** + * Defines a request that can be configured (payload and headers) + * @param + */ +public interface ParameterizableRequest extends Request { + + /** + * Adds additional parameters to send in the request + * @param parameters as a non-null dictionary + * @return itself + */ + com.auth0.api.ParameterizableRequest addParameters(Map parameters); + + /** + * Adds an additional header for the request + * @param name of the header + * @param value of the header + * @return itself + */ + com.auth0.api.ParameterizableRequest addHeader(String name, String value); + +} diff --git a/core/src/main/java/com/auth0/api/Request.java b/core/src/main/java/com/auth0/api/Request.java new file mode 100644 index 00000000..602ea96e --- /dev/null +++ b/core/src/main/java/com/auth0/api/Request.java @@ -0,0 +1,37 @@ +/* + * Request.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api; + +import com.auth0.api.callback.BaseCallback; + +/** + * Defines a request that can be started + * @param + */ +public interface Request { + + void start(BaseCallback callback); + +} diff --git a/core/src/main/java/com/auth0/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/api/RequestBodyBuildException.java new file mode 100644 index 00000000..18c94c6b --- /dev/null +++ b/core/src/main/java/com/auth0/api/RequestBodyBuildException.java @@ -0,0 +1,12 @@ +package com.auth0.api; + +/** + * Exception that wraps errors when creating a body for a request + */ +public class RequestBodyBuildException extends RuntimeException { + + public RequestBodyBuildException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java new file mode 100644 index 00000000..4ad2f6d3 --- /dev/null +++ b/core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java @@ -0,0 +1,469 @@ +/* + * AuthenticationClient.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.authentication; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.auth0.api.ParameterBuilder; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.Request; +import com.auth0.api.internal.RequestFactory; +import com.auth0.core.Application; +import com.auth0.core.Auth0; +import com.auth0.core.DatabaseUser; +import com.auth0.core.Token; +import com.auth0.core.UserProfile; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; + +import java.util.Map; + +import static com.auth0.api.ParameterBuilder.GRANT_TYPE_PASSWORD; + +/** + * API client for Auth0 Authentication API. + * @see Auth API docs + */ +public class AuthenticationAPIClient { + + private static final String TAG = com.auth0.api.authentication.AuthenticationAPIClient.class.getName(); + + private static final String USERNAME_KEY = "username"; + private static final String PASSWORD_KEY = "password"; + private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; + private static final String ID_TOKEN_KEY = "id_token"; + private static final String EMAIL_KEY = "email"; + private static final String REFRESH_TOKEN_KEY = "refresh_token"; + private static final String API_TYPE_KEY = "api_type"; + private static final String DEFAULT_API_TYPE = "app"; + private static final String PHONE_NUMBER_KEY = "phone_number"; + + private final Auth0 auth0; + private final OkHttpClient client; + private final Handler handler; + private final ObjectMapper mapper; + + private String defaultDbConnection = DEFAULT_DB_CONNECTION; + + /** + * Creates a new API client instance providing Auth0 account info. + * @param auth0 account information + */ + public AuthenticationAPIClient(Auth0 auth0) { + this(auth0, new Handler(Looper.getMainLooper())); + } + + /** + * Creates a new API client instance providing Auth0 account info and a handler where all callbacks will be called + * @param auth0 account information + * @param handler where callback will be called with either the response or error from the server + */ + public AuthenticationAPIClient(Auth0 auth0, Handler handler) { + this(auth0, new OkHttpClient(), handler, new ObjectMapper()); + } + + /** + * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). + * @param clientID Your application clientID. + * @param baseURL Auth0's auth API endpoint + * @param configurationURL Auth0's enpoint where App info can be retrieved. + */ + @SuppressWarnings("unused") + public AuthenticationAPIClient(String clientID, String baseURL, String configurationURL) { + this(new Auth0(clientID, baseURL, configurationURL)); + } + + AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, Handler handler, ObjectMapper mapper) { + this.auth0 = auth0; + this.client = client; + this.handler = handler; + this.mapper = mapper; + } + + public String getClientId() { + return auth0.getClientId(); + } + + public String getBaseURL() { + return auth0.getDomainUrl(); + } + + /** + * Set the default DB connection name used. By default is 'Username-Password-Authentication' + * @param defaultDbConnection name to use on every login with DB connection + */ + public void setDefaultDbConnection(String defaultDbConnection) { + this.defaultDbConnection = defaultDbConnection; + } + + /** + * Fetch application information from Auth0 + * @return a Auth0 request to start + */ + public Request fetchApplicationInfo() { + HttpUrl url = HttpUrl.parse(auth0.getConfigurationUrl()).newBuilder() + .addPathSegment("client") + .addPathSegment(auth0.getClientId() + ".js") + .build(); + return RequestFactory.newApplicationInfoRequest(url, client, handler, mapper); + } + + /** + * Log in a user using resource owner endpoint ('/oauth/ro') + * @return a request to configure and start + */ + public ParameterizableRequest loginWithResourceOwner() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("oauth") + .addPathSegment("ro") + .build(); + + Map requestParameters = new ParameterBuilder() + .setClientId(getClientId()) + .setConnection(defaultDbConnection) + .asDictionary(); + ParameterizableRequest request = RequestFactory.POST(url, client, handler, mapper, Token.class) + .addParameters(requestParameters); + Log.d(TAG, "Trying to login using " + url.toString() + " with parameters " + requestParameters); + return request; + } + + /** + * Log in a user with email/username and password using a DB connection and fetch it's profile from Auth0 + * @param usernameOrEmail of the user depending of the type of DB connection + * @param password of the user + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public AuthenticationRequest login(String usernameOrEmail, String password) { + Map requestParameters = new ParameterBuilder() + .set(USERNAME_KEY, usernameOrEmail) + .set(PASSWORD_KEY, password) + .setGrantType(GRANT_TYPE_PASSWORD) + .asDictionary(); + return newAuthenticationRequest(requestParameters); + } + + /** + * Log in a user with a OAuth 'access_token' of a Identity Provider like Facebook or Twitter using '\oauth\access_token' endpoint + * @param token obtained from the IdP + * @param connection that will be used to authenticate the user, e.g. 'facebook' + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public AuthenticationRequest loginWithOAuthAccessToken(String token, String connection) { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("oauth") + .addPathSegment("access_token") + .build(); + + Map parameters = ParameterBuilder.newBuilder() + .setClientId(getClientId()) + .setConnection(connection) + .setAccessToken(token) + .asDictionary(); + + Log.v(TAG, "Performing OAuth access_token login with parameters " + parameters); + + final ParameterizableRequest profileRequest = profileRequest(); + ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, handler, mapper, Token.class) + .addParameters(parameters); + return new AuthenticationRequest(credentialsRequest, profileRequest); + } + + /** + * Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) + * @param phoneNumber where the user received the verification code + * @param verificationCode sent by Auth0 via SMS + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { + Map parameters = ParameterBuilder.newBuilder() + .set(USERNAME_KEY, phoneNumber) + .set(PASSWORD_KEY, verificationCode) + .setGrantType(GRANT_TYPE_PASSWORD) + .setClientId(getClientId()) + .setConnection("sms") + .asDictionary(); + return newAuthenticationRequest(parameters); + } + + /** + * Log in a user using an email and a verification code received via Email (Part of passwordless login flow) + * @param email where the user received the verification code + * @param verificationCode sent by Auth0 via Email + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public AuthenticationRequest loginWithEmail(String email, String verificationCode) { + Map parameters = ParameterBuilder.newBuilder() + .set(USERNAME_KEY, email) + .set(PASSWORD_KEY, verificationCode) + .setGrantType(GRANT_TYPE_PASSWORD) + .setClientId(getClientId()) + .setConnection("email") + .asDictionary(); + return newAuthenticationRequest(parameters); + } + + /** + * Fetch the token information from Auth0 + * @param idToken used to fetch it's information + * @return a request to start + */ + public Request tokenInfo(String idToken) { + Map requestParameters = new ParameterBuilder() + .clearAll() + .set(ID_TOKEN_KEY, idToken) + .asDictionary(); + Log.d(TAG, "Trying to fetch token with parameters " + requestParameters); + return profileRequest() + .addParameters(requestParameters); + } + + /** + * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * @param email of the user and must be non null + * @param password of the user and must be non null + * @param username of the user and must be non null + * @return a request to start + */ + public ParameterizableRequest createUser(String email, String password, String username) { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("dbconnections") + .addPathSegment("signup") + .build(); + Map parameters = new ParameterBuilder() + .set(USERNAME_KEY, username) + .set(EMAIL_KEY, email) + .set(PASSWORD_KEY, password) + .setConnection(defaultDbConnection) + .setClientId(getClientId()) + .asDictionary(); + Log.d(TAG, "Creating user with email " + email + " and username " + username); + return RequestFactory.POST(url, client, handler, mapper, DatabaseUser.class) + .addParameters(parameters); + } + + /** + * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * @param email of the user and must be non null + * @param password of the user and must be non null + * @return a request to start + */ + public ParameterizableRequest createUser(String email, String password) { + return createUser(email, password, null); + } + + /** + * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * and then logs in and fetches it's user profile + * @param email of the user and must be non null + * @param password of the user and must be non null + * @param username of the user and must be non null + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public com.auth0.api.authentication.SignUpRequest signUp(String email, String password, String username) { + ParameterizableRequest createUserRequest = createUser(email, password, username); + AuthenticationRequest authenticationRequest = login(email, password); + return new com.auth0.api.authentication.SignUpRequest(createUserRequest, authenticationRequest); + } + + /** + * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * and then logs in and fetches it's user profile + * @param email of the user and must be non null + * @param password of the user and must be non null + * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + */ + public com.auth0.api.authentication.SignUpRequest signUp(String email, String password) { + ParameterizableRequest createUserRequest = createUser(email, password); + AuthenticationRequest authenticationRequest = login(email, password); + return new SignUpRequest(createUserRequest, authenticationRequest); + } + + /** + * Perform a change password request using '/dbconnections/change_password' + * @param email of the user that changes the password. It's also where the confirmation email will be sent + * @param newPassword to use + * @return a request to configure and start + */ + public ParameterizableRequest changePassword(String email, String newPassword) { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("dbconnections") + .addPathSegment("change_password") + .build(); + + Map parameters = ParameterBuilder.newBuilder() + .set(EMAIL_KEY, email) + .set(PASSWORD_KEY, newPassword) + .setClientId(getClientId()) + .setConnection(defaultDbConnection) + .asDictionary(); + + return RequestFactory.POST(url, client, handler, mapper) + .addParameters(parameters); + } + + /** + * Performs a delegation request + * @return a request to configure and start + */ + public ParameterizableRequest> delegation() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("delegation") + .build(); + Map parameters = ParameterBuilder.newEmptyBuilder() + .clearAll() + .setClientId(getClientId()) + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) + .asDictionary(); + return RequestFactory.rawPOST(url, client, handler, mapper) + .addParameters(parameters); + } + + /** + * Performs a delegation request that will yield a new Auth0 'id_token' + * @param idToken issued by Auth0 for the user. The token must not be expired. + * @return a request to configure and start + */ + public DelegationRequest delegationWithIdToken(String idToken) { + Map parameters = new ParameterBuilder() + .clearAll() + .set(ID_TOKEN_KEY, idToken) + .set(API_TYPE_KEY, DEFAULT_API_TYPE) + .asDictionary(); + ParameterizableRequest> request = delegation() + .addParameters(parameters); + return new DelegationRequest(request); + } + + /** + * Performs a delegation request that will yield a new Auth0 'id_token'. + * Check our refresh token docs for more information + * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. + * @return a request to configure and start + */ + public DelegationRequest delegationWithRefreshToken(String refreshToken) { + Map parameters = new ParameterBuilder() + .clearAll() + .set(REFRESH_TOKEN_KEY, refreshToken) + .set(API_TYPE_KEY, DEFAULT_API_TYPE) + .asDictionary(); + ParameterizableRequest> request = delegation() + .addParameters(parameters); + return new DelegationRequest(request); + } + + /** + * Unlink a user identity calling '/unlink' endpoint + * @param userId of the identity to unlink + * @param accessToken of the main identity obtained after login + * @return a request to start + */ + public Request unlink(String userId, String accessToken) { + Map parameters = new ParameterBuilder() + .clearAll() + .set("clientID", getClientId()) + .set("user_id", userId) + .set("access_token", accessToken) + .asDictionary(); + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("unlink") + .build(); + return RequestFactory.POST(url, client, handler, mapper) + .addParameters(parameters); + } + + /** + * Start a passwordless flow with either Email or SMS + * @return a request to configure and stat + */ + public ParameterizableRequest passwordless() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("passwordless") + .addPathSegment("start") + .build(); + + Map parameters = ParameterBuilder.newBuilder() + .clearAll() + .setClientId(getClientId()) + .asDictionary(); + + return RequestFactory.POST(url, client, handler, mapper) + .addParameters(parameters); + } + + /** + * Start a passwordless flow with either Email + * @param email that will receive a verification code to use for login + * @param useMagicLink whether the email should contain the magic link or the code + * @return a request to configure and start + */ + public ParameterizableRequest passwordlessWithEmail(String email, boolean useMagicLink) { + Map parameters = ParameterBuilder.newBuilder() + .clearAll() + .set(EMAIL_KEY, email) + .set("send", useMagicLink ? "link_android" : "code") + .setConnection("email") + .asDictionary(); + return passwordless() + .addParameters(parameters); + } + + /** + * Start a passwordless flow with SMS + * @param phoneNumber where an SMS with a verification code will be sent + * @param useMagicLink whether the SMS should contain the magic link or the code + * @return a request to configure and stat + */ + public ParameterizableRequest passwordlessWithSMS(String phoneNumber, boolean useMagicLink) { + Map parameters = ParameterBuilder.newBuilder() + .clearAll() + .set(PHONE_NUMBER_KEY, phoneNumber) + .set("send", useMagicLink ? "link_android" : "code") + .setConnection("sms") + .asDictionary(); + return passwordless() + .addParameters(parameters); + } + + private ParameterizableRequest profileRequest() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("tokeninfo") + .build(); + return RequestFactory.POST(url, client, handler, mapper, UserProfile.class); + + } + + private AuthenticationRequest newAuthenticationRequest(Map parameters) { + final ParameterizableRequest credentialsRequest = loginWithResourceOwner() + .addParameters(parameters); + final ParameterizableRequest profileRequest = profileRequest(); + + return new AuthenticationRequest(credentialsRequest, profileRequest); + } + +} diff --git a/core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java new file mode 100644 index 00000000..20ddd4eb --- /dev/null +++ b/core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java @@ -0,0 +1,112 @@ +/* + * AuthenticationRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.authentication; + +import com.auth0.api.ParameterBuilder; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.callback.AuthenticationCallback; +import com.auth0.api.callback.BaseCallback; +import com.auth0.core.Token; +import com.auth0.core.UserProfile; + +import java.util.Map; + +/** + * Represent a Authentication request that consist of a log in and a fetch profile requests + */ +public class AuthenticationRequest { + + private final ParameterizableRequest credentialsRequest; + private final ParameterizableRequest tokenInfoRequest; + + AuthenticationRequest(ParameterizableRequest credentialsRequest, ParameterizableRequest tokenInfoRequest) { + this.credentialsRequest = credentialsRequest; + this.tokenInfoRequest = tokenInfoRequest; + } + + /** + * Adds additional parameters for the login request + * @param parameters as a non-null dictionary + * @return itself + */ + public com.auth0.api.authentication.AuthenticationRequest addParameters(Map parameters) { + credentialsRequest.addParameters(parameters); + return this; + } + + /** + * Set the scope used to authenticate the user + * @param scope value + * @return itself + */ + public com.auth0.api.authentication.AuthenticationRequest setScope(String scope) { + credentialsRequest.addParameters(new ParameterBuilder().clearAll().setScope(scope).asDictionary()); + return this; + } + + /** + * Set the connection used to authenticate + * @param connection name + * @return itself + */ + public com.auth0.api.authentication.AuthenticationRequest setConnection(String connection) { + credentialsRequest.addParameters(new ParameterBuilder().clearAll().setConnection(connection).asDictionary()); + return this; + } + + /** + * Starts the log in request and then fetches the user's profile + * @param callback called on either success or failure + */ + public void start(final AuthenticationCallback callback) { + credentialsRequest.start(new BaseCallback() { + @Override + public void onSuccess(final Token token) { + Map parameters = new ParameterBuilder() + .clearAll() + .set("id_token", token.getIdToken()) + .asDictionary(); + tokenInfoRequest + .addParameters(parameters) + .start(new BaseCallback() { + @Override + public void onSuccess(UserProfile profile) { + callback.onSuccess(profile, token); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } +} diff --git a/core/src/main/java/com/auth0/api/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/api/authentication/DelegationRequest.java new file mode 100644 index 00000000..bc895932 --- /dev/null +++ b/core/src/main/java/com/auth0/api/authentication/DelegationRequest.java @@ -0,0 +1,79 @@ +/* + * DelegationRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.authentication; + +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.callback.BaseCallback; +import com.auth0.api.callback.RefreshIdTokenCallback; + +import java.util.Map; + +/** + * Represent a delegation request for Auth0 tokens that will yield a new 'id_token' + */ +public class DelegationRequest { + + private static final String TOKEN_TYPE_KEY = "token_type"; + private static final String EXPIRES_IN_KEY = "expires_in"; + private static final String ID_TOKEN_KEY = "id_token"; + + private final ParameterizableRequest> request; + + DelegationRequest(ParameterizableRequest> request) { + this.request = request; + } + + /** + * Add additional parameters to be sent in the request + * @param parameters as a non-null dictionary + * @return itself + */ + public com.auth0.api.authentication.DelegationRequest addParameters(Map parameters) { + request.addParameters(parameters); + return this; + } + + /** + * Performs the HTTP request against Auth0 API + * @param callback called either on success or failure + */ + public void start(final RefreshIdTokenCallback callback) { + request.start(new BaseCallback>() { + @Override + public void onSuccess(final Map payload) { + final String id_token = (String) payload.get(ID_TOKEN_KEY); + final String token_type = (String) payload.get(TOKEN_TYPE_KEY); + final Integer expires_in = (Integer) payload.get(EXPIRES_IN_KEY); + callback.onSuccess(id_token, token_type, expires_in); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } + +} diff --git a/core/src/main/java/com/auth0/api/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/api/authentication/SignUpRequest.java new file mode 100644 index 00000000..443c2d85 --- /dev/null +++ b/core/src/main/java/com/auth0/api/authentication/SignUpRequest.java @@ -0,0 +1,105 @@ +/* + * SignUpRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.authentication; + +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.callback.AuthenticationCallback; +import com.auth0.api.callback.BaseCallback; +import com.auth0.core.DatabaseUser; + +import java.util.Map; + +/** + * Represent a request to create a user + log in + fetch user profile. + */ +public class SignUpRequest { + + private final ParameterizableRequest signUpRequest; + private final com.auth0.api.authentication.AuthenticationRequest authenticationRequest; + + SignUpRequest(ParameterizableRequest signUpRequest, AuthenticationRequest authenticationRequest) { + this.signUpRequest = signUpRequest; + this.authenticationRequest = authenticationRequest; + } + + /** + * Add additional parameters for create user request + * @param parameters as a non-null dictionary + * @return itself + */ + public com.auth0.api.authentication.SignUpRequest addSignUpParameters(Map parameters) { + signUpRequest.addParameters(parameters); + return this; + } + + /** + * Add additional parameters for login request + * @param parameters as a non-null dictionary + * @return itself + */ + public com.auth0.api.authentication.SignUpRequest addAuthenticationParameters(Map parameters) { + authenticationRequest.addParameters(parameters); + return this; + } + + /** + * Set the scope used to authenticate the user + * @param scope value + * @return itself + */ + public com.auth0.api.authentication.SignUpRequest setScope(String scope) { + authenticationRequest.setScope(scope); + return this; + } + + /** + * Set the connection used to authenticate + * @param connection name + * @return itself + */ + public com.auth0.api.authentication.SignUpRequest setConnection(String connection) { + authenticationRequest.setConnection(connection); + return this; + } + + /** + * Starts to execute create user request and then logs the user in. + * @param callback called on either success or failure. + */ + public void start(final AuthenticationCallback callback) { + signUpRequest.start(new BaseCallback() { + @Override + public void onSuccess(final DatabaseUser user) { + authenticationRequest + .start(callback); + } + + @Override + public void onFailure(Throwable error) { + callback.onFailure(error); + } + }); + } +} diff --git a/core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java b/core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java new file mode 100644 index 00000000..41b3f2e7 --- /dev/null +++ b/core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java @@ -0,0 +1,19 @@ +package com.auth0.api.callback; + +import com.auth0.core.Token; +import com.auth0.core.UserProfile; + +/** + * Callback for authentication API calls to Auth0 API. + */ +public interface AuthenticationCallback extends Callback { + + /** + * Called when authentication is successful. + * It might include user's profile and token information. + * @param profile User's profile information or null. + * @param token User's token information (e.g. id_token). + */ + void onSuccess(UserProfile profile, Token token); + +} diff --git a/core/src/main/java/com/auth0/api/callback/BaseCallback.java b/core/src/main/java/com/auth0/api/callback/BaseCallback.java new file mode 100644 index 00000000..b114ac56 --- /dev/null +++ b/core/src/main/java/com/auth0/api/callback/BaseCallback.java @@ -0,0 +1,14 @@ +package com.auth0.api.callback; + +/** + * Callback that receives a single value on success. + */ +public interface BaseCallback extends Callback { + + /** + * Method called on success with the payload or null. + * @param payload Request payload or null + */ + void onSuccess(T payload); + +} diff --git a/core/src/main/java/com/auth0/api/callback/Callback.java b/core/src/main/java/com/auth0/api/callback/Callback.java new file mode 100644 index 00000000..edcae44c --- /dev/null +++ b/core/src/main/java/com/auth0/api/callback/Callback.java @@ -0,0 +1,14 @@ +package com.auth0.api.callback; + +/** + * Interface for all callbacks used with Auth0 API clients + */ +public interface Callback { + + /** + * Method called on Auth0 API request failure + * @param error Error with the reason of the failure + */ + void onFailure(Throwable error); + +} diff --git a/core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java b/core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java new file mode 100644 index 00000000..c7e030d0 --- /dev/null +++ b/core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java @@ -0,0 +1,39 @@ +/* + * RefreshIdTokenCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.callback; + +/** + * Callback used in delegation api request for a new Auth0 id_token + */ +public interface RefreshIdTokenCallback extends Callback { + + /** + * Called in successful delegation api call with new id_token + * @param idToken new id_token. + * @param tokenType type of token. + * @param expiresIn when the token expires. + */ + void onSuccess(String idToken, String tokenType, int expiresIn); +} diff --git a/core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java new file mode 100644 index 00000000..0ce908ee --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java @@ -0,0 +1,105 @@ +/* + * ApplicationInfoRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Handler; +import android.util.Log; + +import com.auth0.api.APIClientException; +import com.auth0.api.ParameterizableRequest; +import com.auth0.core.Application; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +import java.io.IOException; +import java.util.Map; + +class ApplicationInfoRequest extends BaseRequest implements Callback { + + private static final String TAG = com.auth0.api.internal.ApplicationInfoRequest.class.getName(); + + public ApplicationInfoRequest(Handler handler, OkHttpClient client, HttpUrl url, ObjectMapper mapper) { + super(handler, url, client, mapper.reader(Application.class), null); + } + + @Override + protected Request doBuildRequest(Request.Builder builder) { + final Request request = builder.build(); + Log.v(TAG, "Fetching application info from " + request.urlString()); + return request; + } + + @Override + public void onFailure(Request request, IOException e) { + postOnFailure(e); + } + + @Override + public void onResponse(Response response) throws IOException { + if (!response.isSuccessful()) { + String message = "Received app info failed response with code " + response.code() + " and body " + response.body().string(); + postOnFailure(new IOException(message)); + return; + } + try { + String json = response.body().string(); + JSONTokener tokenizer = new JSONTokener(json); + tokenizer.skipPast("Auth0.setClient("); + if (!tokenizer.more()) { + postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP")); + return; + } + Object nextValue = tokenizer.nextValue(); + if (!(nextValue instanceof JSONObject)) { + tokenizer.back(); + postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info")); + } + JSONObject jsonObject = (JSONObject) nextValue; + Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject); + Application app = getReader().readValue(jsonObject.toString()); + postOnSuccess(app); + } catch (JSONException | IOException e) { + postOnFailure(new APIClientException("Failed to parse JSONP", e)); + } + } + + @Override + public ParameterizableRequest addParameters(Map parameters) { + return this; + } + + @Override + public ParameterizableRequest addHeader(String name, String value) { + return this; + } +} diff --git a/core/src/main/java/com/auth0/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/api/internal/BaseRequest.java new file mode 100644 index 00000000..1d19d2ff --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/BaseRequest.java @@ -0,0 +1,168 @@ +/* + * ResponseCallbackTask.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Build; +import android.os.Handler; +import android.util.Log; + +import com.auth0.api.APIClientException; +import com.auth0.api.AuthorizableRequest; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.RequestBodyBuildException; +import com.auth0.api.callback.BaseCallback; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +abstract class BaseRequest implements ParameterizableRequest, AuthorizableRequest, Callback { + + private static final String TAG = BaseCallback.class.getName(); + + private final Handler handler; + private final Map headers; + private final Map parameters; + private final HttpUrl url; + private final OkHttpClient client; + private final ObjectReader reader; + private final ObjectWriter writer; + + private BaseCallback callback; + + protected BaseRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer) { + this(handler, url, client, reader, writer, null); + } + + public BaseRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer, BaseCallback callback) { + this.handler = handler; + this.url = url; + this.client = client; + this.reader = reader; + this.writer = writer; + this.callback = callback; + this.headers = new HashMap<>(); + this.parameters = new HashMap<>(); + this.headers.put("User-Agent", String.format("Android %s (%s %s;)", Build.VERSION.RELEASE, Build.MODEL, Build.MANUFACTURER)); + } + + protected void setCallback(BaseCallback callback) { + this.callback = callback; + } + + protected void postOnSuccess(final T payload) { + handler.post(new CallbackTask(callback) { + @Override + public void run() { + this.callback.onSuccess(payload); + } + }); + } + + protected final void postOnFailure(final Throwable error) { + Log.e(TAG, "Failed to make request to " + url, error); + handler.post(new CallbackTask(callback) { + @Override + public void run() { + this.callback.onFailure(error); + } + }); + } + + protected Request.Builder newBuilder() { + final Request.Builder builder = new Request.Builder() + .url(url); + for (Map.Entry entry : headers.entrySet()) { + builder.addHeader(entry.getKey(), entry.getValue()); + } + return builder; + } + + protected Map getParameters() { + return parameters; + } + + protected ObjectReader getReader() { + return reader; + } + + protected RequestBody buildBody() throws RequestBodyBuildException { + return com.auth0.api.internal.JsonRequestBodyBuilder.createBody(parameters, writer); + } + + private static abstract class CallbackTask implements Runnable { + protected final BaseCallback callback; + + protected CallbackTask(BaseCallback callback) { + this.callback = callback; + } + } + + @Override + public void onFailure(Request request, IOException e) { + postOnFailure(e); + } + + @Override + public ParameterizableRequest addHeader(String name, String value) { + headers.put(name, value); + return this; + } + + @Override + public AuthorizableRequest setBearer(String jwt) { + addHeader("Authorization", "Bearer " + jwt); + return this; + } + + @Override + public ParameterizableRequest addParameters(Map parameters) { + if (parameters != null) { + this.parameters.putAll(parameters); + } + return this; + } + + @Override + public void start(BaseCallback callback) { + setCallback(callback); + try { + Request request = doBuildRequest(newBuilder()); + client.newCall(request).enqueue(this); + } catch (RequestBodyBuildException e) { + Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); + callback.onFailure(new APIClientException("Failed to send request to " + url.toString(), e)); + } + } + + protected abstract Request doBuildRequest(Request.Builder builder) throws RequestBodyBuildException; +} diff --git a/core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java b/core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java new file mode 100644 index 00000000..1abf76ea --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java @@ -0,0 +1,47 @@ +/* + * JsonRequestBodyBuilder.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import com.auth0.api.RequestBodyBuildException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +/** + * Converts a POJO to JSON stored in a {@link RequestBody} + */ +abstract class JsonRequestBodyBuilder { + + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + public static RequestBody createBody(Object pojo, ObjectWriter writer) throws RequestBodyBuildException { + try { + return RequestBody.create(JSON, writer.writeValueAsBytes(pojo)); + } catch (JsonProcessingException e) { + throw new RequestBodyBuildException("Failed to convert " + pojo.getClass().getName() + " to JSON", e); + } + } +} diff --git a/core/src/main/java/com/auth0/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/api/internal/RequestFactory.java new file mode 100644 index 00000000..6bc11f60 --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/RequestFactory.java @@ -0,0 +1,95 @@ +/* + * RequestFactory.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Handler; + +import com.auth0.api.AuthorizableRequest; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.Request; +import com.auth0.core.Application; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; + +import java.util.Map; + +public class RequestFactory { + + private static String CLIENT_INFO; + + private RequestFactory() {} + + public static void setClientInfo(String clientInfo) { + CLIENT_INFO = clientInfo; + } + + public static ParameterizableRequest GET(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "GET", clazz)); + } + + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "POST", clazz)); + } + + public static ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { + final com.auth0.api.internal.SimpleRequest> request = new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "POST"); + addMetricHeader(request); + return request; + } + + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { + return addMetricHeader(new com.auth0.api.internal.VoidRequest(handler, url, client, mapper, "POST")); + } + + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, String jwt) { + final AuthorizableRequest request = new com.auth0.api.internal.VoidRequest(handler, url, client, mapper, "POST") + .setBearer(jwt); + return addMetricHeader(request); + } + + public static ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "PUT", clazz)); + } + + public static ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "GET", clazz)); + } + + public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "DELETE", clazz)); + } + + public static Request newApplicationInfoRequest(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { + return addMetricHeader(new com.auth0.api.internal.ApplicationInfoRequest(handler, client, url, mapper)); + } + + private static ParameterizableRequest addMetricHeader(ParameterizableRequest request) { + if (CLIENT_INFO != null) { + request.addHeader("Auth0-Client", CLIENT_INFO); + } + return request; + } +} diff --git a/core/src/main/java/com/auth0/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/api/internal/SimpleRequest.java new file mode 100644 index 00000000..9a67bf9c --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/SimpleRequest.java @@ -0,0 +1,99 @@ +/* + * AuthenticationRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Handler; +import android.util.Log; + +import com.auth0.api.APIClientException; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.Request; +import com.auth0.api.RequestBodyBuildException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + +class SimpleRequest extends BaseRequest implements Request, ParameterizableRequest, Callback { + + private static final String TAG = com.auth0.api.internal.SimpleRequest.class.getName(); + + private final ObjectReader errorReader; + private final String method; + + public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { + super(handler, url, client, mapper.reader(clazz), mapper.writer()); + this.errorReader = mapper.reader(new TypeReference>() {}); + this.method = httpMethod; + } + + public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { + super(handler, url, client, mapper.reader(new TypeReference>() {}), mapper.writer()); + this.errorReader = mapper.reader(new TypeReference>() { + }); + this.method = httpMethod; + } + + @Override + public void onResponse(Response response) throws IOException { + Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); + final InputStream byteStream = response.body().byteStream(); + if (!response.isSuccessful()) { + Throwable throwable; + try { + Map payload = errorReader.readValue(byteStream); + throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); + } catch (IOException e) { + throwable = new APIClientException("Request failed", response.code(), null); + } + postOnFailure(throwable); + return; + } + + try { + Log.d(TAG, "Received successful response from " + response.request().urlString()); + T payload = getReader().readValue(byteStream); + postOnSuccess(payload); + } catch (IOException e) { + postOnFailure(new APIClientException("Request failed", response.code(), null)); + } + } + + @Override + protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request.Builder builder) throws RequestBodyBuildException { + RequestBody body = buildBody(); + return newBuilder() + .method(method, body) + .build(); + } +} diff --git a/core/src/main/java/com/auth0/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/api/internal/VoidRequest.java new file mode 100644 index 00000000..15e5e0b2 --- /dev/null +++ b/core/src/main/java/com/auth0/api/internal/VoidRequest.java @@ -0,0 +1,84 @@ +/* + * VoidRequest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Handler; +import android.util.Log; + +import com.auth0.api.APIClientException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + +class VoidRequest extends BaseRequest implements Callback { + + private static final String TAG = com.auth0.api.internal.VoidRequest.class.getName(); + + private final ObjectReader errorReader; + private final String httpMethod; + + public VoidRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { + super(handler, url, client, null, mapper.writer()); + this.httpMethod = httpMethod; + this.errorReader = mapper.reader(new TypeReference>() { + }); + } + + @Override + public void onResponse(Response response) throws IOException { + Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); + final InputStream byteStream = response.body().byteStream(); + if (!response.isSuccessful()) { + Throwable throwable; + try { + Map payload = errorReader.readValue(byteStream); + throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); + } catch (IOException e) { + throwable = new APIClientException("Request failed", response.code(), null); + } + postOnFailure(throwable); + return; + } + + postOnSuccess(null); + } + + @Override + protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request.Builder builder) { + RequestBody body = buildBody(); + return newBuilder() + .method(httpMethod, body) + .build(); + } +} diff --git a/core/src/main/java/com/auth0/core/Application.java b/core/src/main/java/com/auth0/core/Application.java new file mode 100644 index 00000000..157dcf65 --- /dev/null +++ b/core/src/main/java/com/auth0/core/Application.java @@ -0,0 +1,183 @@ +package com.auth0.core; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +import static com.auth0.util.CheckHelper.checkArgument; + +/** + * Class with your Auth0's application information and the list of enabled connections (DB, Social, Enterprise, Passwordless). + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Application { + + private String id; + private String tenant; + private String authorizeURL; + private String callbackURL; + private String subscription; + private boolean hasAllowedOrigins; + private List strategies; + private List socialStrategies; + private List enterpriseStrategies; + private Strategy databaseStrategy; + + /** + * Creates a new application instance + * @param id app id. + * @param tenant name of the tenant who owns the app. + * @param authorizeURL url used to authorize during oauth flow. + * @param callbackURL url used after a oauth flow. + * @param subscription type of subscription. + * @param hasAllowedOrigins if the app allows other origins + * @param strategies list of the strategies enabled for the app (Social, DB, etc). + */ + @JsonCreator + public Application(@JsonProperty(value = "id") String id, + @JsonProperty(value = "tenant") String tenant, + @JsonProperty(value = "authorize") String authorizeURL, + @JsonProperty(value = "callback") String callbackURL, + @JsonProperty(value = "subscription") String subscription, + @JsonProperty(value = "hasAllowedOrigins") boolean hasAllowedOrigins, + @JsonProperty(value = "strategies") List strategies) { + checkArgument(id != null, "id must be non-null"); + checkArgument(tenant != null, "tenant must be non-null"); + checkArgument(authorizeURL != null, "authorize must be non-null"); + checkArgument(strategies != null && strategies.size() > 0, "Must have at least 1 strategy"); + this.id = id; + this.tenant = tenant; + this.authorizeURL = authorizeURL; + this.callbackURL = callbackURL; + this.subscription = subscription; + this.hasAllowedOrigins = hasAllowedOrigins; + this.strategies = strategies; + this.socialStrategies = new ArrayList<>(); + this.enterpriseStrategies = new ArrayList<>(); + for(Strategy strategy: strategies) { + if (Strategies.Auth0.getName().equals(strategy.getName())) { + this.databaseStrategy = strategy; + } else { + switch (strategy.getType()) { + case SOCIAL: + this.socialStrategies.add(strategy); + break; + case ENTERPRISE: + this.enterpriseStrategies.add(strategy); + break; + } + } + } + } + + /** + * Returns the id of the application. + * @return an ID + */ + public String getId() { + return id; + } + + /** + * Returns the name of the tenant who owns the app. + * @return name of the tenant + */ + public String getTenant() { + return tenant; + } + + /** + * Returns url used to authorize during oauth flow. + * @return a url string + */ + public String getAuthorizeURL() { + return authorizeURL; + } + + /** + * Returns url used after a oauth flow. + * @return a url string + */ + public String getCallbackURL() { + return callbackURL; + } + + /** + * Returns the type of subscription + * @return type of subscription + */ + public String getSubscription() { + return subscription; + } + + /** + * Returns if the app allows other origins. + * @return hasAllowedOrigins flag + */ + public boolean isHasAllowedOrigins() { + return hasAllowedOrigins; + } + + /** + * Returns all available auth strategies for the app. + * @return + */ + public List getStrategies() { + return new ArrayList<>(strategies); + } + + /** + * Returns the Database strategy of the app. + * @return DB strategy + */ + public Strategy getDatabaseStrategy() { + return databaseStrategy; + } + + /** + * Returns the social strategies of the app. + * @return list of social strategies + */ + public List getSocialStrategies() { + return new ArrayList<>(socialStrategies); + } + + /** + * Returns the social enterprise of the app. + * @return list of enterprise strategies + */ + public List getEnterpriseStrategies() { + return new ArrayList<>(enterpriseStrategies); + } + + /** + * Returns a {@link com.auth0.core.Strategy} by its name + * @param name strategy name + * @return a {@link com.auth0.core.Strategy} + */ + public Strategy strategyForName(String name) { + for (Strategy strategy: this.strategies) { + if (strategy.getName().equals(name)) { + return strategy; + } + } + return null; + } + + /** + * Returns the strategy by one of its connections + * @param connection a connection + * @return a {@link com.auth0.core.Strategy} + */ + public Strategy strategyForConnection(Connection connection) { + for (Strategy strategy: this.strategies) { + if (strategy.getConnections().contains(connection)) { + return strategy; + } + } + return null; + } +} diff --git a/core/src/main/java/com/auth0/core/Auth0.java b/core/src/main/java/com/auth0/core/Auth0.java new file mode 100644 index 00000000..72275bae --- /dev/null +++ b/core/src/main/java/com/auth0/core/Auth0.java @@ -0,0 +1,105 @@ +/* + * Auth0.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.core; + +import android.net.Uri; + +import com.auth0.api.APIClient; +import com.auth0.api.authentication.AuthenticationAPIClient; + +public class Auth0 { + + private static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; + private static final String DOT_AUTH0_DOT_COM = ".auth0.com"; + + private final String clientId; + private final String domainUrl; + private final String configurationUrl; + + public Auth0(String clientId, String domain) { + this(clientId, domain, null); + } + + public Auth0(String clientId, String domain, String configurationDomain) { + this.clientId = clientId; + this.domainUrl = ensureUrlString(domain); + this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl); + } + + private String resolveConfiguration(String configurationDomain, String domainUrl) { + String url = ensureUrlString(configurationDomain); + if (configurationDomain == null && domainUrl != null) { + final Uri domainUri = Uri.parse(domainUrl); + final String host = domainUri.getHost(); + if (host.endsWith(DOT_AUTH0_DOT_COM)) { + String[] parts = host.split("\\."); + if (parts.length > 3) { + url = "https://cdn." + parts[parts.length-3] + DOT_AUTH0_DOT_COM; + } else { + url = AUTH0_US_CDN_URL; + } + } else { + url = domainUrl; + } + } + return url; + } + + private String ensureUrlString(String url) { + String safeUrl = null; + if (url != null) { + safeUrl = url.startsWith("http") ? url : "https://" + url; + } + return safeUrl; + } + + public String getClientId() { + return clientId; + } + + public String getDomainUrl() { + return domainUrl; + } + + public String getConfigurationUrl() { + return configurationUrl; + } + + @Deprecated + public APIClient newAPIClient() { + return new APIClient(this.clientId, this.domainUrl, this.configurationUrl); + } + + public AuthenticationAPIClient newAuthenticationAPIClient() { + return new AuthenticationAPIClient(this); + } + + public String getAuthorizeUrl() { + return Uri.parse(domainUrl).buildUpon() + .path("authorize") + .build() + .toString(); + } +} diff --git a/core/src/main/java/com/auth0/core/Connection.java b/core/src/main/java/com/auth0/core/Connection.java new file mode 100644 index 00000000..97331b1d --- /dev/null +++ b/core/src/main/java/com/auth0/core/Connection.java @@ -0,0 +1,133 @@ +package com.auth0.core; + +import android.os.Parcel; +import android.os.Parcelable; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.auth0.util.CheckHelper.checkArgument; + +/** + * Class with a Auth0 connection info + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Connection implements Parcelable { + + private String name; + + private Map values; + + /** + * Creates a new connection instance + * @param values Connection values + */ + @JsonCreator + public Connection(Map values) { + checkArgument(values != null && values.size() > 0, "Must have at least one value"); + final String name = (String) values.remove("name"); + checkArgument(name != null, "Must have a non-null name"); + this.name = name; + this.values = values; + } + + /** + * Returns all the connection values + * @return connection values + */ + public Map getValues() { + return values; + } + + public String getName() { + return name; + } + + /** + * Returns a value using its key + * @param key a key + * @param type of value to return + * @return a value + */ + @SuppressWarnings("unchecked") + public T getValueForKey(String key) { + return (T) this.values.get(key); + } + + /** + * Returns a boolean value using its key + * @param key a key + * @return the value of the flag + */ + public boolean booleanForKey(String key) { + Boolean value = getValueForKey(key); + if (value == null) { + return false; + } + return value; + } + + /** + * Get set of domain if the connection is Enterprise + * @return a set with all domains configured + */ + public Set getDomainSet() { + Set domains = new HashSet<>(); + String domain = getValueForKey("domain"); + if (domain != null) { + domains.add(domain.toLowerCase()); + List aliases = getValueForKey("domain_aliases"); + if (aliases != null) { + for (String alias: aliases) { + domains.add(alias.toLowerCase()); + } + } + } + return domains; + } + + @SuppressWarnings("unchecked") + protected Connection(Parcel in) { + name = in.readString(); + if (in.readByte() == 0x01) { + values = (Map) in.readSerializable(); + } else { + values = new HashMap<>(); + } + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(name); + if (values == null || values.isEmpty()) { + dest.writeByte((byte) 0x00); + } else { + dest.writeByte((byte) (0x01)); + dest.writeSerializable(new HashMap<>(values)); + } + } + + @SuppressWarnings("unused") + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public com.auth0.core.Connection createFromParcel(Parcel in) { + return new com.auth0.core.Connection(in); + } + + @Override + public com.auth0.core.Connection[] newArray(int size) { + return new com.auth0.core.Connection[size]; + } + }; +} diff --git a/core/src/main/java/com/auth0/core/DatabaseUser.java b/core/src/main/java/com/auth0/core/DatabaseUser.java new file mode 100644 index 00000000..d1ad8592 --- /dev/null +++ b/core/src/main/java/com/auth0/core/DatabaseUser.java @@ -0,0 +1,59 @@ +/* + * DatabaseUser.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.core; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Value holder for Database Sign Up operation + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DatabaseUser { + + private final String email; + private final String username; + private final boolean emailVerified; + + public DatabaseUser(@JsonProperty(value = "email", required = true) String email, + @JsonProperty("username") String username, + @JsonProperty("email_verified") boolean emailVerified) { + this.email = email; + this.username = username; + this.emailVerified = emailVerified; + } + + public String getEmail() { + return email; + } + + public String getUsername() { + return username; + } + + public boolean isEmailVerified() { + return emailVerified; + } +} diff --git a/core/src/main/java/com/auth0/core/Strategies.java b/core/src/main/java/com/auth0/core/Strategies.java new file mode 100644 index 00000000..34f18cf6 --- /dev/null +++ b/core/src/main/java/com/auth0/core/Strategies.java @@ -0,0 +1,106 @@ +package com.auth0.core; + +import static com.auth0.core.Strategies.Type.DATABASE; +import static com.auth0.core.Strategies.Type.ENTERPRISE; +import static com.auth0.core.Strategies.Type.PASSWORDLESS; +import static com.auth0.core.Strategies.Type.SOCIAL; + +/** + * An enum with all strategies available in Auth0 + */ +public enum Strategies { + Auth0("auth0", DATABASE), + + Email("email", PASSWORDLESS), + SMS("sms", PASSWORDLESS), + + Amazon("amazon", SOCIAL), + AOL("aol", SOCIAL), + Baidu("baidu", SOCIAL), + Box("box", SOCIAL), + Dwolla("dwolla", SOCIAL), + EBay("ebay", SOCIAL), + Evernote("evernote", SOCIAL), + EvernoteSandbox("evernote-sandbox", SOCIAL), + Exact("exact", SOCIAL), + Facebook("facebook", SOCIAL), + Fitbit("fitbit", SOCIAL), + Github("github", SOCIAL), + GooglePlus("google-oauth2", SOCIAL), + Instagram("instagram", SOCIAL), + Linkedin("linkedin", SOCIAL), + Miicard("miicard", SOCIAL), + Paypal("paypal", SOCIAL), + PlanningCenter("planningcenter", SOCIAL), + RenRen("renren", SOCIAL), + Salesforce("salesforce", SOCIAL), + SalesforceSandbox("salesforce-sandbox", SOCIAL), + Shopify("shopify", SOCIAL), + Soundcloud("soundcloud", SOCIAL), + TheCity("thecity", SOCIAL), + TheCitySandbox("thecity-sandbox", SOCIAL), + ThirtySevenSignals("thirtysevensignals", SOCIAL), + Twitter("twitter", SOCIAL), + VK("vkontakte", SOCIAL), + Weibo("weibo", SOCIAL), + WindowsLive("windowslive", SOCIAL), + Wordpress("wordpress", SOCIAL), + Yahoo("yahoo", SOCIAL), + Yammer("yammer", SOCIAL), + Yandex("yandex", SOCIAL), + + ActiveDirectory("ad", ENTERPRISE), + ADFS("adfs", ENTERPRISE), + Auth0LDAP("auth0-adldap", ENTERPRISE), + Custom("custom", ENTERPRISE), + GoogleApps("google-apps", ENTERPRISE), + GoogleOpenId("google-openid", ENTERPRISE), + IP("ip", ENTERPRISE), + MSCRM("mscrm", ENTERPRISE), + Office365("office365", ENTERPRISE), + PingFederate("pingfederate", ENTERPRISE), + SAMLP("samlp", ENTERPRISE), + Sharepoint("sharepoint", ENTERPRISE), + Waad("waad", ENTERPRISE), + + UnknownSocial("unknown-social", SOCIAL); + + private String name; + private Type type; + + Strategies(String name, Type type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public Type getType() { + return type; + } + + public static com.auth0.core.Strategies fromName(String name) { + com.auth0.core.Strategies strategy = null; + for (com.auth0.core.Strategies str: values()) { + if (str.getName().equals(name)) { + strategy = str; + break; + } + } + + // if strategy not found, assume it's a new social type + if (strategy == null) + strategy = UnknownSocial; + + return strategy; + } + + public enum Type { + DATABASE, + SOCIAL, + ENTERPRISE, + PASSWORDLESS + } +} diff --git a/core/src/main/java/com/auth0/core/Strategy.java b/core/src/main/java/com/auth0/core/Strategy.java new file mode 100644 index 00000000..f06e007a --- /dev/null +++ b/core/src/main/java/com/auth0/core/Strategy.java @@ -0,0 +1,44 @@ +package com.auth0.core; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * Class with Auth0 authentication strategy info + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Strategy { + + private String name; + private List connections; + private Strategies strategyMetadata; + + @JsonCreator + public Strategy(@JsonProperty(value = "name", required = true) String name, + @JsonProperty(value = "connections", required = true) List connections) { + this.name = name; + this.connections = connections; + this.strategyMetadata = Strategies.fromName(name); + } + + public String getName() { + return name; + } + + public List getConnections() { + return connections; + } + + public Strategies.Type getType() { + return this.strategyMetadata.getType(); + } + + public boolean isResourceOwnerEnabled() { + return Strategies.ActiveDirectory.getName().equals(name) + || Strategies.ADFS.getName().equals(name) + || Strategies.Waad.getName().equals(name); + } +} diff --git a/core/src/main/java/com/auth0/core/Token.java b/core/src/main/java/com/auth0/core/Token.java new file mode 100644 index 00000000..0759233d --- /dev/null +++ b/core/src/main/java/com/auth0/core/Token.java @@ -0,0 +1,78 @@ +package com.auth0.core; + +import android.os.Parcel; +import android.os.Parcelable; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Class that holds a user's token information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Token implements Parcelable { + + private String idToken; + private String accessToken; + private String type; + private String refreshToken; + + public Token(@JsonProperty(value = "id_token", required = true) String idToken, + @JsonProperty(value = "access_token") String accessToken, + @JsonProperty(value = "token_type") String type, + @JsonProperty(value = "refresh_token") String refreshToken) { + this.idToken = idToken; + this.accessToken = accessToken; + this.type = type; + this.refreshToken = refreshToken; + } + + public String getIdToken() { + return idToken; + } + + public String getAccessToken() { + return accessToken; + } + + public String getType() { + return type; + } + + public String getRefreshToken() { + return refreshToken; + } + + protected Token(Parcel in) { + idToken = in.readString(); + accessToken = in.readString(); + type = in.readString(); + refreshToken = in.readString(); + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(idToken); + dest.writeString(accessToken); + dest.writeString(type); + dest.writeString(refreshToken); + } + + @SuppressWarnings("unused") + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public com.auth0.core.Token createFromParcel(Parcel in) { + return new com.auth0.core.Token(in); + } + + @Override + public com.auth0.core.Token[] newArray(int size) { + return new com.auth0.core.Token[size]; + } + }; +} diff --git a/core/src/main/java/com/auth0/core/UserIdentity.java b/core/src/main/java/com/auth0/core/UserIdentity.java new file mode 100644 index 00000000..52dd8d2a --- /dev/null +++ b/core/src/main/java/com/auth0/core/UserIdentity.java @@ -0,0 +1,144 @@ +package com.auth0.core; + +import android.os.Parcel; +import android.os.Parcelable; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.HashMap; +import java.util.Map; + +/** + * Class that holds the information from a Identity Provider like Facebook or Twitter. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class UserIdentity implements Parcelable { + + private static final String USER_ID_KEY = "user_id"; + private static final String CONNECTION_KEY = "connection"; + private static final String PROVIDER_KEY = "provider"; + private static final String IS_SOCIAL_KEY = "isSocial"; + private static final String ACCESS_TOKEN_KEY = "access_token"; + private static final String ACCESS_TOKEN_SECRET_KEY = "access_token_secret"; + private static final String PROFILE_DATA_KEY = "profileData"; + private String id; + private String connection; + private String provider; + private boolean social; + private String accessToken; + private String accessTokenSecret; + private Map profileInfo; + + @SuppressWarnings("unchecked") + public UserIdentity(Map values) { + final Object idValue = values.get(USER_ID_KEY); + if (idValue != null) { + this.id = idValue.toString(); + } + this.connection = (String) values.get(CONNECTION_KEY); + this.provider = (String) values.get(PROVIDER_KEY); + this.social = (boolean) values.get(IS_SOCIAL_KEY); + this.accessToken = (String) values.get(ACCESS_TOKEN_KEY); + this.accessTokenSecret = (String) values.get(ACCESS_TOKEN_SECRET_KEY); + this.profileInfo = (Map) values.get(PROFILE_DATA_KEY); + } + + @JsonCreator + public UserIdentity(@JsonProperty(value = USER_ID_KEY) String id, + @JsonProperty(value = CONNECTION_KEY) String connection, + @JsonProperty(value = PROVIDER_KEY) String provider, + @JsonProperty(value = IS_SOCIAL_KEY) boolean social, + @JsonProperty(value = ACCESS_TOKEN_KEY) String accessToken, + @JsonProperty(value = ACCESS_TOKEN_SECRET_KEY) String accessTokenSecret, + @JsonProperty(value = PROFILE_DATA_KEY) Map profileInfo) { + this.id = id; + this.connection = connection; + this.provider = provider; + this.social = social; + this.accessToken = accessToken; + this.accessTokenSecret = accessTokenSecret; + this.profileInfo = profileInfo; + } + + public String getId() { + return id; + } + + public String getConnection() { + return connection; + } + + public String getProvider() { + return provider; + } + + public boolean isSocial() { + return social; + } + + public String getAccessToken() { + return accessToken; + } + + public String getAccessTokenSecret() { + return accessTokenSecret; + } + + public Map getProfileInfo() { + return profileInfo; + } + + public String getUserIdentityId() { + return String.format("%s|%s", this.provider, this.id); + } + + protected UserIdentity(Parcel in) { + id = in.readString(); + connection = in.readString(); + provider = in.readString(); + social = in.readByte() != 0x00; + accessToken = in.readString(); + accessTokenSecret = in.readString(); + if (in.readByte() == 0x01) { + profileInfo = (Map) in.readSerializable(); + } else { + profileInfo = new HashMap(); + } + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(id); + dest.writeString(connection); + dest.writeString(provider); + dest.writeByte((byte) (social ? 0x01 : 0x00)); + dest.writeString(accessToken); + dest.writeString(accessTokenSecret); + if (profileInfo == null) { + dest.writeByte((byte) 0x00); + } else { + dest.writeByte((byte) (0x01)); + dest.writeSerializable(new HashMap(profileInfo)); + } + } + + @SuppressWarnings("unused") + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public com.auth0.core.UserIdentity createFromParcel(Parcel in) { + return new com.auth0.core.UserIdentity(in); + } + + @Override + public com.auth0.core.UserIdentity[] newArray(int size) { + return new com.auth0.core.UserIdentity[size]; + } + }; +} diff --git a/core/src/main/java/com/auth0/core/UserProfile.java b/core/src/main/java/com/auth0/core/UserProfile.java new file mode 100644 index 00000000..16b38580 --- /dev/null +++ b/core/src/main/java/com/auth0/core/UserProfile.java @@ -0,0 +1,172 @@ +package com.auth0.core; + +import android.os.Parcel; +import android.os.Parcelable; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + +import static com.auth0.util.CheckHelper.checkArgument; + +/** + * Class that holds the information of a user's profile + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class UserProfile implements Parcelable { + + private String id; + private String name; + private String nickname; + private String email; + private String pictureURL; + private Date createdAt; + private Map extraInfo; + private List identities; + + @JsonCreator + @SuppressWarnings("unchecked") + public UserProfile(Map values) { + checkArgument(values != null, "must supply non-null values"); + HashMap info = new HashMap(values); + String id = (String) info.remove("user_id"); + checkArgument(id != null, "profile must have a user id"); + this.id = id; + this.name = (String) info.remove("name"); + this.nickname = (String) info.remove("nickname"); + this.email = (String) info.remove("email"); + this.pictureURL = (String) info.remove("picture"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + String created_at = (String) info.remove("created_at"); + this.createdAt = created_at != null ? sdf.parse(created_at) : null; + } catch (ParseException e) { + throw new IllegalArgumentException("Invalid created_at value", e); + } + this.identities = buildIdentities((List>) info.remove("identities")); + this.extraInfo = info; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getNickname() { + return nickname; + } + + public String getEmail() { + return email; + } + + public String getPictureURL() { + return pictureURL; + } + + public Date getCreatedAt() { + return createdAt; + } + + /** + * Returns extra information of the profile. + * @return + */ + public Map getExtraInfo() { + return new HashMap<>(extraInfo); + } + + /** + * List of the identities from a Identity Provider associated to the user. + * @return + */ + public List getIdentities() { + return identities; + } + + private List buildIdentities(List> values) { + if (values == null) { + return Collections.emptyList(); + } + List identities = new ArrayList<>(values.size()); + for (Map value: values) { + identities.add(new UserIdentity(value)); + } + return identities; + } + + @SuppressWarnings("unchecked") + protected UserProfile(Parcel in) { + id = in.readString(); + name = in.readString(); + nickname = in.readString(); + email = in.readString(); + pictureURL = in.readString(); + long tmpCreatedAt = in.readLong(); + createdAt = tmpCreatedAt != -1 ? new Date(tmpCreatedAt) : null; + if (in.readByte() == 0x01) { + identities = new ArrayList(); + in.readList(identities, UserIdentity.class.getClassLoader()); + } else { + identities = null; + } + if (in.readByte() == 0x01) { + extraInfo = (Map) in.readSerializable(); + } else { + extraInfo = new HashMap(); + } + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(id); + dest.writeString(name); + dest.writeString(nickname); + dest.writeString(email); + dest.writeString(pictureURL); + dest.writeLong(createdAt != null ? createdAt.getTime() : -1L); + if (identities == null) { + dest.writeByte((byte) (0x00)); + } else { + dest.writeByte((byte) (0x01)); + dest.writeList(identities); + } + if (extraInfo == null) { + dest.writeByte((byte) 0x00); + } else { + dest.writeByte((byte) (0x01)); + dest.writeSerializable(new HashMap(extraInfo)); + } + } + + @SuppressWarnings("unused") + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public com.auth0.core.UserProfile createFromParcel(Parcel in) { + return new com.auth0.core.UserProfile(in); + } + + @Override + public com.auth0.core.UserProfile[] newArray(int size) { + return new com.auth0.core.UserProfile[size]; + } + }; +} diff --git a/core/src/main/java/com/auth0/util/CheckHelper.java b/core/src/main/java/com/auth0/util/CheckHelper.java new file mode 100644 index 00000000..c0871cb4 --- /dev/null +++ b/core/src/main/java/com/auth0/util/CheckHelper.java @@ -0,0 +1,37 @@ +/* + * Preconditions.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +/** + * A helper to check constructor arguments. + */ +public class CheckHelper { + + public static void checkArgument(boolean expression, String message) throws RuntimeException { + if (!expression) { + throw new IllegalArgumentException(message); + } + } +} diff --git a/core/src/test/java/com/auth0/api/ParameterBuilderTest.java b/core/src/test/java/com/auth0/api/ParameterBuilderTest.java new file mode 100644 index 00000000..81998760 --- /dev/null +++ b/core/src/test/java/com/auth0/api/ParameterBuilderTest.java @@ -0,0 +1,139 @@ +package com.auth0.api; + +import android.os.Build; + +import com.auth0.android.BuildConfig; +import com.auth0.api.ParameterBuilder; + +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class ParameterBuilderTest { + + public static final String CLIENT_ID = "CLIENT ID"; + public static final String GRANT_TYPE = "password"; + public static final String CONNECTION = "AD"; + public static final String DEVICE = "ANDROID TEST DEVICE"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + private ParameterBuilder builder; + + @Before + public void setUp() throws Exception { + this.builder = ParameterBuilder.newBuilder(); + } + + @Test + public void shouldInstantiateWithNoArguments() throws Exception { + assertThat(new ParameterBuilder(), is(notNullValue())); + assertThat(ParameterBuilder.newBuilder(), is(notNullValue())); + } + + @Test + public void shouldInstantiateWithDefaultScope() throws Exception { + assertThat(new ParameterBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(ParameterBuilder.newBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + } + + @Test + public void shouldInstantiateWithArguments() throws Exception { + assertThat(new ParameterBuilder(new HashMap()), is(notNullValue())); + assertThat(ParameterBuilder.newBuilder(new HashMap()), is(notNullValue())); + } + + @Test + public void shouldFailToInstantiateWithNullParameters() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); + new ParameterBuilder(null); + } + + @Test + public void shouldFailToInstantiateWithNullParametersInFactoryMethod() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); + ParameterBuilder.newBuilder(null); + } + + @Test + public void shouldSetClientID() throws Exception { + assertThat(builder.setClientId(CLIENT_ID).asDictionary(), hasEntry("client_id", CLIENT_ID)); + } + + @Test + public void shouldSetScope() throws Exception { + Map parameters = builder.setScope(ParameterBuilder.SCOPE_OPENID).asDictionary(); + assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); + assertThat(parameters, not(hasEntry("device", Build.MODEL))); + } + + @Test + public void shouldSetDevice() throws Exception { + Map parameters = builder.setDevice(DEVICE).asDictionary(); + assertThat(parameters, hasEntry("device", DEVICE)); + } + + @Test + public void shouldSetScopeWithOfflineAccess() throws Exception { + Map parameters = builder.setScope(ParameterBuilder.SCOPE_OFFLINE_ACCESS).asDictionary(); + assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(parameters, hasEntry("device", Build.MODEL)); + } + + @Test + public void shouldSetGrantType() throws Exception { + assertThat(builder.setGrantType(GRANT_TYPE).asDictionary(), hasEntry("grant_type", GRANT_TYPE)); + } + + @Test + public void shouldSetConnection() throws Exception { + assertThat(builder.setConnection(CONNECTION).asDictionary(), hasEntry("connection", CONNECTION)); + } + + @Test + public void shouldAddArbitraryEntry() throws Exception { + assertThat(builder.set("key", "value").asDictionary(), hasEntry("key", "value")); + } + + @Test + public void shouldAddAllFromDictionary() throws Exception { + Map parameters = new HashMap<>(); + parameters.put("key", "value"); + assertThat(builder.addAll(parameters).asDictionary(), hasEntry("key", "value")); + } + + @Test + public void shouldDoNothingWhenAddingNullParameters() throws Exception { + assertThat(builder.addAll(null).asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + } + + @Test + public void shouldProvideADictionaryCopy() throws Exception { + Map parameters = builder.setClientId(CLIENT_ID).asDictionary(); + parameters.put("key", "value"); + assertThat(builder.asDictionary(), not(hasEntry("key", "value"))); + } + + private static Matcher> hasEntry(String key, Object value) { + return Matchers.hasEntry(key, value); + } +} diff --git a/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java new file mode 100644 index 00000000..cbbd3003 --- /dev/null +++ b/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java @@ -0,0 +1,589 @@ +/* + * AuthenticationAPIClientTest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.authentication; + +import android.os.Handler; + +import com.auth0.android.BuildConfig; +import com.auth0.api.ParameterBuilder; +import com.auth0.api.authentication.AuthenticationAPIClient; +import com.auth0.core.Application; +import com.auth0.core.Auth0; +import com.auth0.core.DatabaseUser; +import com.auth0.core.Token; +import com.auth0.core.UserProfile; +import com.auth0.util.AuthenticationAPI; +import com.auth0.util.MockAuthenticationCallback; +import com.auth0.util.MockBaseCallback; +import com.auth0.util.MockRefreshIdTokenCallback; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.mockwebserver.RecordedRequest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.HashMap; +import java.util.Map; + +import static com.auth0.util.AuthenticationAPI.GENERIC_TOKEN; +import static com.auth0.util.AuthenticationAPI.ID_TOKEN; +import static com.auth0.util.AuthenticationAPI.NEW_ID_TOKEN; +import static com.auth0.util.AuthenticationAPI.REFRESH_TOKEN; +import static com.auth0.util.AuthenticationCallbackMatcher.hasTokenAndProfile; +import static com.auth0.util.CallbackMatcher.hasNoError; +import static com.auth0.util.CallbackMatcher.hasNoPayloadOfType; +import static com.auth0.util.CallbackMatcher.hasPayload; +import static com.auth0.util.CallbackMatcher.hasPayloadOfType; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class AuthenticationAPIClientTest { + + private static final String CLIENT_ID = "CLIENTID"; + private static final String DOMAIN = "samples.auth0.com"; + private static final String CONNECTION = "DB"; + + private AuthenticationAPIClient client; + + private AuthenticationAPI mockAPI; + + @Before + public void setUp() throws Exception { + mockAPI = new AuthenticationAPI(); + final String domain = mockAPI.getDomain(); + Auth0 auth0 = new Auth0(CLIENT_ID, domain, domain); + Handler handler = mock(Handler.class); + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Runnable runnable = (Runnable) invocation.getArguments()[0]; + runnable.run(); + return null; + } + }).when(handler).post(any(Runnable.class)); + client = new AuthenticationAPIClient(auth0, handler); + } + + @After + public void tearDown() throws Exception { + mockAPI.shutdown(); + } + + @Test + public void shouldCreateClientWithAccountInfo() throws Exception { + AuthenticationAPIClient client = new AuthenticationAPIClient(new Auth0(CLIENT_ID, DOMAIN)); + assertThat(client, is(notNullValue())); + assertThat(client.getClientId(), equalTo(CLIENT_ID)); + assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); + } + + @Test + public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { + mockAPI.willReturnValidApplicationResponse(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + + assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); + assertThat(callback, hasPayloadOfType(Application.class)); + } + + @Test + public void shoulFailWithInvalidJSON() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shoulFailWithInvalidJSONP() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shouldFailWithFailedStatusCode() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); + final MockBaseCallback callback = new MockBaseCallback<>(); + + client.fetchApplicationInfo() + .start(callback); + + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shouldLoginWithResourceOwner() throws Exception { + mockAPI.willReturnSuccessfulLogin(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection("DB") + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .setScope(ParameterBuilder.SCOPE_OPENID) + .asDictionary(); + client.loginWithResourceOwner() + .addParameters(parameters) + .start(callback); + + assertThat(callback, hasPayloadOfType(Token.class)); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "DB")); + assertThat(body, hasEntry("grant_type", "password")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "notapassword")); + assertThat(body, hasEntry("scope", "openid")); + } + + @Test + public void shouldFailLoginWithResourceOwner() throws Exception { + mockAPI.willReturnFailedLogin(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection(CONNECTION) + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .asDictionary(); + client.loginWithResourceOwner() + .addParameters(parameters) + .start(callback); + + assertThat(callback, hasNoPayloadOfType(Token.class)); + } + + @Test + public void shouldLoginWithUserAndPassword() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + + client.login("support@auth0.com", "voidpassword") + .start(callback); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldFetchTokenInfo() throws Exception { + mockAPI.willReturnTokenInfo(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + client.tokenInfo("ID_TOKEN") + .start(callback); + + assertThat(callback, hasPayloadOfType(UserProfile.class)); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/tokeninfo")); + } + + @Test + public void shouldLoginWithOAuthAccessToken() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithOAuthAccessToken("fbtoken", "facebook") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/access_token")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "facebook")); + assertThat(body, hasEntry("access_token", "fbtoken")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldLoginWithPhoneNumber() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithPhoneNumber("+10101010101", "1234") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "sms")); + assertThat(body, hasEntry("username", "+10101010101")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldLoginWithEmailOnly() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithEmail("support@auth0.com", "1234") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "email")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldCreateUser() throws Exception { + mockAPI.willReturnSuccessfulSignUp(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.createUser("support@auth0.com", "123123123", "support") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasPayloadOfType(DatabaseUser.class)); + + } + + @Test + public void shouldCreateUserWithoutUsername() throws Exception { + mockAPI.willReturnSuccessfulSignUp(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.createUser("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasPayloadOfType(DatabaseUser.class)); + + } + + @Test + public void shouldSignUpUser() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.signUp("support@auth0.com", "123123123", "support") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldSignUpUserWithoutUsername() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.signUp("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldChangePassword() throws Exception { + mockAPI.willReturnSuccessfulChangePassword(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.changePassword("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldCallDelegation() throws Exception { + mockAPI.willReturnGenericDelegationToken(); + + final MockBaseCallback> callback = new MockBaseCallback<>(); + client.delegation() + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + + Map payload = new HashMap<>(); + payload.put("token", GENERIC_TOKEN); + assertThat(callback, hasPayload(payload)); + } + + @Test + public void shouldGetNewIdTokenWithIdToken() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + client.delegationWithIdToken(ID_TOKEN) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("id_token", ID_TOKEN)); + + assertThat(callback, hasPayload(NEW_ID_TOKEN)); + } + + @Test + public void shouldGetNewIdTokenWithRefreshToken() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + client.delegationWithRefreshToken(REFRESH_TOKEN) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); + + assertThat(callback, hasPayload(NEW_ID_TOKEN)); + } + + @Test + public void shouldUnlinkAccount() throws Exception { + mockAPI.willReturnSuccessfulUnlinkAccount(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.unlink("user id", "access token") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/unlink")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("clientID", CLIENT_ID)); + assertThat(body, hasEntry("user_id", "user id")); + assertThat(body, hasEntry("access_token", "access token")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldStartPasswordless() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + final Map parameters = new ParameterBuilder() + .clearAll() + .setConnection("email") + .set("send", "code") + .set("email", "support@auth0.com") + .asDictionary(); + client.passwordless() + .addParameters(parameters) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendEmailCode() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", false) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendEmailLink() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", true) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendSMSCode() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", false) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendSMSLink() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", true) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + + private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { + return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java new file mode 100644 index 00000000..116977f5 --- /dev/null +++ b/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java @@ -0,0 +1,124 @@ +/* + * CallbackHandlerTest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.api.internal; + +import android.os.Handler; + +import com.auth0.android.BuildConfig; +import com.auth0.api.ParameterizableRequest; +import com.auth0.api.callback.BaseCallback; +import com.auth0.api.internal.BaseRequest; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.io.IOException; +import java.util.Map; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class BaseRequestTest { + + private BaseRequest baseRequest; + + @Mock + private Handler handler; + @Mock + private BaseCallback callback; + @Mock + private Throwable throwable; + @Mock + private OkHttpClient client; + @Mock + private ObjectReader reader; + @Mock + private ObjectWriter writer; + @Captor + private ArgumentCaptor captor; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + HttpUrl url = HttpUrl.parse("https://auth0.com"); + baseRequest = new BaseRequest(handler, url, client, reader, writer, callback) { + @Override + protected Request doBuildRequest(Request.Builder builder) { + return null; + } + + @Override + public void onResponse(Response response) throws IOException { + + } + + @Override + public void start(BaseCallback callback) { + + } + + @Override + public ParameterizableRequest addParameters(Map parameters) { + return null; + } + }; + } + + @Test + public void shouldPostOnSuccess() throws Exception { + baseRequest.postOnSuccess("OK"); + verify(handler).post(captor.capture()); + Runnable runnable = captor.getValue(); + runnable.run(); + verify(callback).onSuccess(eq("OK")); + verifyNoMoreInteractions(callback, handler); + } + + @Test + public void shouldPostOnFailure() throws Exception { + baseRequest.postOnFailure(throwable); + verify(handler).post(captor.capture()); + Runnable runnable = captor.getValue(); + runnable.run(); + verify(callback).onFailure(eq(throwable)); + verifyNoMoreInteractions(callback, handler); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/core/ApplicationTest.java b/core/src/test/java/com/auth0/core/ApplicationTest.java new file mode 100644 index 00000000..9789c5ad --- /dev/null +++ b/core/src/test/java/com/auth0/core/ApplicationTest.java @@ -0,0 +1,97 @@ +package com.auth0.core; + +import com.auth0.android.BuildConfig; +import com.auth0.core.Application; +import com.auth0.core.Connection; +import com.auth0.core.Strategies; +import com.auth0.core.Strategy; +import com.google.common.collect.Lists; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.Arrays; +import java.util.List; + +import static com.auth0.core.Strategies.ADFS; +import static com.auth0.core.Strategies.Auth0; +import static com.auth0.core.Strategies.Facebook; +import static com.auth0.core.Strategies.Office365; +import static com.auth0.core.Strategies.SAMLP; +import static com.auth0.core.Strategies.Twitter; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class ApplicationTest { + + public static final String ID = "ID"; + public static final String TENANT = "TENANT"; + public static final String AUTHORIZE_URL = "AUTHORIZE"; + public static final String CALLBACK_URL = "CALLBACK"; + public static final String SUBSCRIPTION = "SUBSCRIPTION"; + public static final boolean HAS_ALLOWED_ORIGINS = true; + + @Test + public void shouldInstantiateApplication() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application, is(notNullValue())); + } + + @Test + public void shouldHaveApplicationInfo() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application.getId(), equalTo(ID)); + assertThat(application.getTenant(), equalTo(TENANT)); + assertThat(application.getAuthorizeURL(), equalTo(AUTHORIZE_URL)); + assertThat(application.getCallbackURL(), equalTo(CALLBACK_URL)); + assertThat(application.getSubscription(), equalTo(SUBSCRIPTION)); + assertThat(application.isHasAllowedOrigins(), equalTo(HAS_ALLOWED_ORIGINS)); + } + + @Test + public void shouldReturnDatabaseStrategy() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application.getDatabaseStrategy(), is(notNullValue())); + assertThat(application.getDatabaseStrategy().getName(), equalTo(Auth0.getName())); + } + + @Test + public void shouldReturnNoDatabaseStrategy() throws Exception { + Application application = newApplicationWithStrategies(Facebook); + assertThat(application.getDatabaseStrategy(), is(nullValue())); + } + + @Test + public void shouldReturnSocialStrategies() throws Exception { + Application application = newApplicationWithStrategies(Facebook, Twitter, Auth0); + assertThat(application.getSocialStrategies().size(), equalTo(2)); + } + + @Test + public void shouldReturnEnterpriseStrategies() throws Exception { + Application application = newApplicationWithStrategies(Auth0, ADFS, SAMLP, Office365); + assertThat(application.getEnterpriseStrategies().size(), equalTo(3)); + } + + private static Strategy newStrategyFor(Strategies strategyMetadata) { + return new Strategy(strategyMetadata.getName(), Arrays.asList(mock(Connection.class))); + } + + private static Application newApplicationWithStrategies(Strategies... list) { + List strategies = Lists.newArrayList(); + for (Strategies str: list) { + strategies.add(newStrategyFor(str)); + } + Application application = new Application(ID, TENANT, AUTHORIZE_URL, CALLBACK_URL, SUBSCRIPTION, HAS_ALLOWED_ORIGINS, strategies); + return application; + } +} diff --git a/core/src/test/java/com/auth0/core/Auth0Test.java b/core/src/test/java/com/auth0/core/Auth0Test.java new file mode 100644 index 00000000..540ae1c0 --- /dev/null +++ b/core/src/test/java/com/auth0/core/Auth0Test.java @@ -0,0 +1,116 @@ +/* + * Auth0Test.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.core; + +import com.auth0.android.BuildConfig; +import com.auth0.api.APIClient; +import com.auth0.core.Auth0; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertThat; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class Auth0Test { + + private static final String CLIENT_ID = "CLIENT_ID"; + private static final String DOMAIN = "samples.auth0.com"; + private static final String CONFIG_DOMAIN_CUSTOM = "config.mydomain.com"; + private static final String EU_DOMAIN = "samples.eu.auth0.com"; + private static final String AU_DOMAIN = "samples.au.auth0.com"; + private static final String OTHER_DOMAIN = "samples-test.other-subdomain.other.auth0.com"; + + @Test + public void shouldBuildWithClientIdAndDomain() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.auth0.com")); + } + + @Test + public void shouldBuildWithConfigurationDomainToo() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN, CONFIG_DOMAIN_CUSTOM); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://config.mydomain.com")); + } + + @Test + public void shouldHandleEUInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, EU_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.eu.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.eu.auth0.com")); + } + + @Test + public void shouldHandleAUInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, AU_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.au.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.au.auth0.com")); + } + + @Test + public void shouldHandleOtherInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, OTHER_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples-test.other-subdomain.other.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.other.auth0.com")); + } + + @Test + public void shouldHandleNonAuth0Domain() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, "mydomain.com"); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://mydomain.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://mydomain.com")); + } + + @Test + public void shouldBuildNewClient() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + APIClient client = auth0.newAPIClient(); + assertThat(client, is(notNullValue())); + assertThat(client.getConfigurationURL(), startsWith("https://cdn.auth0.com/")); + assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); + assertThat(client.getClientID(), equalTo(CLIENT_ID)); + } + + @Test + public void shouldReturnAuthorizeUrl() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + assertThat(auth0.getAuthorizeUrl(), equalTo("https://samples.auth0.com/authorize")); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/core/ConnectionTest.java b/core/src/test/java/com/auth0/core/ConnectionTest.java new file mode 100644 index 00000000..582fe943 --- /dev/null +++ b/core/src/test/java/com/auth0/core/ConnectionTest.java @@ -0,0 +1,135 @@ +package com.auth0.core; + +import com.auth0.android.BuildConfig; +import com.auth0.core.Connection; +import com.google.common.collect.Maps; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.Arrays; +import java.util.Map; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class ConnectionTest { + + public static final String CONNECTION_NAME = "Username-Password"; + public static final Object VALUE = "value"; + public static final String KEY = "key"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void shouldBuildConnectionWithName() { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertNotNull(connection); + assertThat(connection.getName(), equalTo(CONNECTION_NAME)); + } + + @Test + public void shouldBuildConnectionWithValues() { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + assertThat(connection.getValues(), hasEntry(KEY, VALUE)); + } + + @Test + public void shouldNotStoreNameInValues() throws Exception { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertThat(connection.getValues(), not(hasKey("name"))); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldRaiseExceptionWhenNameIsNull() { + Map values = null; + new Connection(values); + } + + @Test + public void shouldReturnValueFromKey() { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + String value = connection.getValueForKey(KEY); + assertThat(value, equalTo(VALUE)); + } + + @Test + public void shouldReturnBooleanValueFromKey() { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put(KEY, true); + Connection connection = new Connection(values); + boolean value = connection.booleanForKey(KEY); + assertThat(value, is(true)); + } + + @Test + public void shouldReturnDefaultBooleanValueFromKey() { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + boolean value = connection.booleanForKey(KEY); + assertThat(value, is(false)); + } + + @Test + public void shouldRaiseExceptionWhenValueIsNotBoolean() { + expectedException.expect(ClassCastException.class); + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + connection.booleanForKey(KEY); + } + + @Test + public void shouldReturnDomainNameInSet() throws Exception { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put("domain", "domain.com"); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet(), hasItem("domain.com")); + } + + @Test + public void shouldReturnAllDomainNamesAsSet() throws Exception { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + values.put("domain", "domain.com"); + values.put("domain_aliases", Arrays.asList("domain2.com", "domain3.com")); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet(), hasItems("domain.com", "domain2.com", "domain3.com")); + } + + @Test + public void shouldReturnEmptySetWithNoDomainName() throws Exception { + Map values = Maps.newHashMap(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet().isEmpty(), is(true)); + } +} diff --git a/core/src/test/java/com/auth0/core/StrategiesTest.java b/core/src/test/java/com/auth0/core/StrategiesTest.java new file mode 100644 index 00000000..aaaa83a9 --- /dev/null +++ b/core/src/test/java/com/auth0/core/StrategiesTest.java @@ -0,0 +1,27 @@ +package com.auth0.core; + +import com.auth0.android.BuildConfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static org.junit.Assert.assertEquals; + + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class StrategiesTest { + @Test + public void shouldReturnUnknownSocial() { + Strategies unknownSocial = Strategies.fromName("this-strategy-does-not-exist"); + assertEquals(unknownSocial.getType(), Strategies.Type.SOCIAL); + } + + @Test + public void shouldReturnValidDatabaseStrategy() { + Strategies auth0Database = Strategies.fromName("auth0"); + assertEquals(auth0Database.getType(), Strategies.Type.DATABASE); + } +} diff --git a/core/src/test/java/com/auth0/core/UserProfileTest.java b/core/src/test/java/com/auth0/core/UserProfileTest.java new file mode 100644 index 00000000..84e20e43 --- /dev/null +++ b/core/src/test/java/com/auth0/core/UserProfileTest.java @@ -0,0 +1,128 @@ +package com.auth0.core; + +import com.auth0.android.BuildConfig; +import com.auth0.core.UserIdentity; +import com.auth0.core.UserProfile; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) +public class UserProfileTest { + + public static final String USER_ID = "IOU a user id"; + public static final String NAME = "Somebody Someone"; + public static final String NICKNAME = "somebody"; + public static final String EMAIL = "somebody@somwhere.com"; + public static final String CREATED_AT = "2014-07-06T18:33:49.005Z"; + public static final String PICTURE_URL = "http://somewhere.com/pic.jpg"; + public static final Object EXTRA_VALUE = "extra_value"; + public static final long CREATED_AT_TIMESTAMP = 1404671629005l; + public static final String FACEBOOK = "facebook"; + public static final String TOKEN = "token"; + public static final String SECRET = "secret"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void shouldRaiseExceptionWithNullValuesWhenCreatingInstance() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalTo("must supply non-null values")); + new UserProfile((HashMap)null); + } + + @Test + public void shouldRaiseExceptionWithNoUserIdWhenCreatingInstance() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalTo("profile must have a user id")); + new UserProfile(new HashMap()); + } + + @Test + public void shouldInstantiateProfileWithId() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + } + + @Test + public void shouldInstantiateWithBasicProfileInfo() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + values.put("name", NAME); + values.put("nickname", NICKNAME); + values.put("email", EMAIL); + values.put("picture", PICTURE_URL); + values.put("created_at", CREATED_AT); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getName(), equalTo(NAME)); + assertThat(profile.getNickname(), equalTo(NICKNAME)); + assertThat(profile.getEmail(), equalTo(EMAIL)); + assertThat(profile.getPictureURL(), equalTo(PICTURE_URL)); + assertThat(profile.getCreatedAt().getTime(), equalTo(CREATED_AT_TIMESTAMP)); + assertThat(profile.getExtraInfo().size(), equalTo(0)); + } + + @Test + public void shouldHandleExtraProfileInfo() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + values.put("extra_key", EXTRA_VALUE); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getExtraInfo(), hasEntry("extra_key", EXTRA_VALUE)); + } + + @Test + public void shouldHandleIdentities() throws Exception { + Map values = new HashMap(); + Map identityValue = new HashMap<>(); + Map profileData = new HashMap<>(); + identityValue.put("user_id", USER_ID); + identityValue.put("connection", FACEBOOK); + identityValue.put("provider", FACEBOOK); + identityValue.put("isSocial", true); + identityValue.put("access_token", TOKEN); + identityValue.put("access_token_secret", SECRET); + identityValue.put("profileData", profileData); + profileData.put("name", "John Doe"); + + values.put("user_id", USER_ID); + values.put("identities", Collections.singletonList(identityValue)); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getIdentities(), hasSize(1)); + UserIdentity identity = profile.getIdentities().get(0); + assertThat(identity, isA(UserIdentity.class)); + assertThat(identity.getId(), equalTo(USER_ID)); + assertThat(identity.getProvider(), equalTo(FACEBOOK)); + assertThat(identity.getConnection(), equalTo(FACEBOOK)); + assertThat(identity.getAccessToken(), equalTo(TOKEN)); + assertThat(identity.getAccessTokenSecret(), equalTo(SECRET)); + } + + private void assertValidProfile(UserProfile profile) { + assertThat(profile, is(notNullValue())); + assertThat(profile.getId(), equalTo(USER_ID)); + } +} diff --git a/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java b/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java new file mode 100644 index 00000000..ff859426 --- /dev/null +++ b/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java @@ -0,0 +1,81 @@ +/* + * APIExceptionMather.java + * + * Copyright (c) 2014 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.auth0.api.APIClientException; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; + +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; + +public class APIClientExceptionMatcher extends BaseMatcher { + + private Matcher causeMatcher; + private Matcher statusCodeMatcher; + private Matcher> errorMatcher; + + private APIClientExceptionMatcher() {} + + private APIClientExceptionMatcher(Matcher causeMatcher, Matcher statusCodeMatcher, Matcher> errorMatcher) { + this.causeMatcher = causeMatcher; + this.statusCodeMatcher = statusCodeMatcher; + this.errorMatcher = errorMatcher; + } + + @Override + public boolean matches(Object o) { + APIClientException exception = (APIClientException) o; + return causeMatcher.matches(exception.getCause()) + && statusCodeMatcher.matches(exception.getStatusCode()) + && errorMatcher.matches(exception.getResponseError()); + } + + @Override + public void describeTo(Description description) { + description + .appendText("APIClientException with values: ") + .appendDescriptionOf(causeMatcher) + .appendText(" ") + .appendDescriptionOf(statusCodeMatcher) + .appendText(" ") + .appendDescriptionOf(errorMatcher) + .appendText(" "); + } + + public static Matcher hasGenericErrorWith(int statusCode, Throwable cause) { + return new APIClientExceptionMatcher(equalTo(cause), equalTo(statusCode), Matchers.>equalTo(new HashMap())); + } + + public static Matcher hasErrorWith(int statusCode, Throwable cause, Object error) { + return new APIClientExceptionMatcher(equalTo(cause), equalTo(statusCode), hasEntry("error", error)); + } +} diff --git a/core/src/test/java/com/auth0/util/AuthenticationAPI.java b/core/src/test/java/com/auth0/util/AuthenticationAPI.java new file mode 100644 index 00000000..437ab1f7 --- /dev/null +++ b/core/src/test/java/com/auth0/util/AuthenticationAPI.java @@ -0,0 +1,174 @@ +/* + * AuthenticationAPI.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; + +import java.io.IOException; + +public class AuthenticationAPI { + + public static final String REFRESH_TOKEN = "REFRESH_TOKEN"; + public static final String ID_TOKEN = "ID_TOKEN"; + public static final String ACCESS_TOKEN = "ACCESS_TOKEN"; + public static final String BEARER = "BEARER"; + public static final String GENERIC_TOKEN = "GENERIC_TOKEN"; + public static final String NEW_ID_TOKEN = "NEW_ID_TOKEN"; + public static final int EXPIRES_IN = 1234567890; + public static final String TOKEN_TYPE = "TOKEN_TYPE"; + + private MockWebServer server; + + public AuthenticationAPI() throws IOException { + this.server = new MockWebServer(); + this.server.start(); + } + + public String getDomain() { + return server.url("/").toString(); + } + + public void shutdown() throws IOException { + this.server.shutdown(); + } + + public RecordedRequest takeRequest() throws InterruptedException { + return server.takeRequest(); + } + + public AuthenticationAPI willReturnValidApplicationResponse() { + return willReturnApplicationResponseWithBody("Auth0.setClient({\"id\":\"CLIENTID\",\"tenant\":\"overmind\",\"subscription\":\"free\",\"authorize\":\"https://samples.auth0.com/authorize\",\"callback\":\"http://localhost:3000/\",\"hasAllowedOrigins\":true,\"strategies\":[{\"name\":\"twitter\",\"connections\":[{\"name\":\"twitter\"}]}]});", 200); + } + + public AuthenticationAPI willReturnSuccessfulChangePassword() { + server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulUnlinkAccount() { + server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); + return this; + } + + public AuthenticationAPI willReturnGenericDelegationToken() { + String json = "{\n" + + " \"token\": \"" + GENERIC_TOKEN + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulPasswordlessStart() { + String json = "{\n" + + " \"phone+number\": \"+1098098098\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnNewIdToken() { + String json = "{\n" + + " \"id_token\": \"" + NEW_ID_TOKEN + "\",\n" + + " \"expires_in\": " + EXPIRES_IN + ",\n" + + " \"token_type\": \"" + TOKEN_TYPE + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulSignUp() { + String json = "{\n" + + " \"_id\": \"gjsmgdkjs72jljsf2dsdhh\", \n" + + " \"email\": \"support@auth0.com\", \n" + + " \"email_verified\": false, \n" + + " \"username\": \"support\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulLogin() { + String json = "{\n" + + " \"refresh_token\": \"" + REFRESH_TOKEN + "\",\n" + + " \"id_token\": \"" + ID_TOKEN + "\",\n" + + " \"access_token\": \"" + ACCESS_TOKEN + "\",\n" + + " \"token_type\": \"" + BEARER + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnFailedLogin() { + String json = "{\n" + + " \"error\": \"invalid_request\",\n" + + " \"error_description\": \"a random error\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 400)); + return this; + } + + public AuthenticationAPI willReturnTokenInfo() { + String json = "{\n" + + " \"email\": \"p@p.xom\",\n" + + " \"email_verified\": false,\n" + + " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + + " \"user_id\": \"auth0|53b995f8bce68d9fc900099c\",\n" + + " \"name\": \"p@p.xom\",\n" + + " \"nickname\": \"p\",\n" + + " \"identities\": [\n" + + " {\n" + + " \"user_id\": \"53b995f8bce68d9fc900099c\",\n" + + " \"provider\": \"auth0\",\n" + + " \"connection\": \"Username-Password-Authentication\",\n" + + " \"isSocial\": false\n" + + " }\n" + + " ],\n" + + " \"created_at\": \"2014-07-06T18:33:49.005Z\",\n" + + " \"username\": \"p\",\n" + + " \"updated_at\": \"2015-09-30T19:43:48.499Z\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnApplicationResponseWithBody(String body, int statusCode) { + MockResponse response = new MockResponse() + .setResponseCode(statusCode) + .addHeader("Content-Type", "application/x-javascript") + .setBody(body); + server.enqueue(response); + return this; + } + + private MockResponse responseWithJSON(String json, int statusCode) { + return new MockResponse() + .setResponseCode(statusCode) + .addHeader("Content-Type", "application/json") + .setBody(json); + } + +} diff --git a/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java b/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java new file mode 100644 index 00000000..54600eb0 --- /dev/null +++ b/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java @@ -0,0 +1,79 @@ +/* + * AuthenticationCallbackMatcher.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.auth0.core.Token; +import com.auth0.core.UserProfile; +import com.jayway.awaitility.core.ConditionTimeoutException; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +import static com.jayway.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +public class AuthenticationCallbackMatcher extends BaseMatcher { + + private final Matcher tokenMatcher; + private final Matcher profileMatcher; + private final Matcher errorMatcher; + + public AuthenticationCallbackMatcher(Matcher tokenMatcher, Matcher profileMatcher, Matcher errorMatcher) { + this.tokenMatcher = tokenMatcher; + this.profileMatcher = profileMatcher; + this.errorMatcher = errorMatcher; + } + + @Override + public boolean matches(Object item) { + MockAuthenticationCallback callback = (MockAuthenticationCallback) item; + try { + await().until(callback.token(), tokenMatcher); + await().until(callback.profile(), profileMatcher); + await().until(callback.error(), errorMatcher); + return true; + } catch (ConditionTimeoutException e) { + return false; + } + } + + @Override + public void describeTo(Description description) { + description + .appendText("successful method be called"); + } + + public static Matcher hasTokenAndProfile() { + return new AuthenticationCallbackMatcher(is(notNullValue(Token.class)), is(notNullValue(UserProfile.class)), is(nullValue(Throwable.class))); + } + + public static Matcher hasNeitherTokeNorProfile() { + return new AuthenticationCallbackMatcher(is(nullValue(Token.class)), is(nullValue(UserProfile.class)), is(notNullValue(Throwable.class))); + } + +} diff --git a/core/src/test/java/com/auth0/util/CallbackMatcher.java b/core/src/test/java/com/auth0/util/CallbackMatcher.java new file mode 100644 index 00000000..59e2fb4a --- /dev/null +++ b/core/src/test/java/com/auth0/util/CallbackMatcher.java @@ -0,0 +1,87 @@ +/* + * CallbackMatcher.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.jayway.awaitility.core.ConditionTimeoutException; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +import static com.jayway.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +public class CallbackMatcher extends BaseMatcher> { + private final Matcher payloadMatcher; + private final Matcher errorMatcher; + + public CallbackMatcher( Matcher payloadMatcher, Matcher errorMatcher) { + this.payloadMatcher = payloadMatcher; + this.errorMatcher = errorMatcher; + } + + @Override + @SuppressWarnings("unchecked") + public boolean matches(Object item) { + MockBaseCallback callback = (MockBaseCallback) item; + try { + await().until(callback.payload(), payloadMatcher); + await().until(callback.error(), errorMatcher); + return true; + } catch (ConditionTimeoutException e) { + return false; + } + } + + @Override + public void describeTo(Description description) { + description + .appendText("successful method be called"); + } + + public static Matcher> hasPayloadOfType(Class clazz) { + return new CallbackMatcher<>(isA(clazz), is(nullValue(Throwable.class))); + } + + public static Matcher> hasPayload(T payload) { + return new CallbackMatcher<>(equalTo(payload), is(nullValue(Throwable.class))); + } + + public static Matcher> hasNoPayloadOfType(Class clazz) { + return new CallbackMatcher<>(is(nullValue(clazz)), is(notNullValue(Throwable.class))); + } + + public static Matcher> hasNoError() { + return new CallbackMatcher<>(is(nullValue(Void.class)), is(nullValue(Throwable.class))); + } + + public static Matcher> hasError() { + return new CallbackMatcher<>(is(nullValue(Void.class)), is(notNullValue(Throwable.class))); + } +} diff --git a/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java b/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java new file mode 100644 index 00000000..b3574d6b --- /dev/null +++ b/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java @@ -0,0 +1,76 @@ +/* + * MockAuthenticationCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.auth0.api.callback.AuthenticationCallback; +import com.auth0.core.Token; +import com.auth0.core.UserProfile; + +import java.util.concurrent.Callable; + +public class MockAuthenticationCallback implements AuthenticationCallback { + + private Token token; + private UserProfile profile; + private Throwable error; + + @Override + public void onSuccess(UserProfile profile, Token token) { + this.token = token; + this.profile = profile; + } + + @Override + public void onFailure(Throwable error) { + this.error = error; + } + + public Callable token() { + return new Callable() { + @Override + public Token call() throws Exception { + return token; + } + }; + } + + public Callable profile() { + return new Callable() { + @Override + public UserProfile call() throws Exception { + return profile; + } + }; + } + + public Callable error() { + return new Callable() { + @Override + public Throwable call() throws Exception { + return error; + } + }; + } +} diff --git a/core/src/test/java/com/auth0/util/MockBaseCallback.java b/core/src/test/java/com/auth0/util/MockBaseCallback.java new file mode 100644 index 00000000..fe34b526 --- /dev/null +++ b/core/src/test/java/com/auth0/util/MockBaseCallback.java @@ -0,0 +1,63 @@ +/* + * MockBaseCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.auth0.api.callback.BaseCallback; + +import java.util.concurrent.Callable; + +public class MockBaseCallback implements BaseCallback { + + private T payload; + private Throwable error; + + @Override + public void onSuccess(T payload) { + this.payload = payload; + } + + @Override + public void onFailure(Throwable error) { + this.error = error; + } + + public Callable payload() { + return new Callable() { + @Override + public T call() throws Exception { + return payload; + } + }; + } + + public Callable error() { + return new Callable() { + @Override + public Throwable call() throws Exception { + return error; + } + }; + } +} diff --git a/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java b/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java new file mode 100644 index 00000000..37bd52b6 --- /dev/null +++ b/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java @@ -0,0 +1,36 @@ +/* + * MockRefreshIdTokenCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.util; + +import com.auth0.api.callback.RefreshIdTokenCallback; + +public class MockRefreshIdTokenCallback extends MockBaseCallback implements RefreshIdTokenCallback { + + @Override + public void onSuccess(String idToken, String tokenType, int expiresIn) { + onSuccess(idToken); + } + +} From 9686ff3c5f89fafc6d85c09849082fca487459f0 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Fri, 8 Jan 2016 15:09:11 -0300 Subject: [PATCH 04/89] Remove everything android related and deprecated classes Move to package com.auth0.java to differentiate from the android impl Remove tests for now --- core/build.gradle | 1 + .../main/java/com/auth0/api/APIClient.java | 368 ----------- .../com/auth0/api/AuthenticatedAPIClient.java | 116 ---- .../java/com/auth0/api/BaseAPIClient.java | 75 --- .../{ => java}/api/APIClientException.java | 4 +- .../{ => java}/api/AuthorizableRequest.java | 4 +- .../{ => java}/api/ParameterBuilder.java | 39 +- .../api/ParameterizableRequest.java | 6 +- .../com/auth0/{ => java}/api/Request.java | 4 +- .../api/RequestBodyBuildException.java | 2 +- .../AuthenticationAPIClient.java | 70 +-- .../authentication/AuthenticationRequest.java | 20 +- .../api/authentication/DelegationRequest.java | 10 +- .../api/authentication/SignUpRequest.java | 20 +- .../api/callback/AuthenticationCallback.java | 6 +- .../{ => java}/api/callback/BaseCallback.java | 2 +- .../{ => java}/api/callback/Callback.java | 2 +- .../api/callback/RefreshIdTokenCallback.java | 2 +- .../api/internal/ApplicationInfoRequest.java | 21 +- .../{ => java}/api/internal/BaseRequest.java | 44 +- .../api/internal/JsonRequestBodyBuilder.java | 4 +- .../api/internal/RequestFactory.java | 48 +- .../api/internal/SimpleRequest.java | 24 +- .../{ => java}/api/internal/VoidRequest.java | 14 +- .../auth0/{ => java}/core/Application.java | 10 +- .../java/com/auth0/{ => java}/core/Auth0.java | 21 +- .../com/auth0/{ => java}/core/Connection.java | 54 +- .../auth0/{ => java}/core/DatabaseUser.java | 2 +- .../com/auth0/{ => java}/core/Strategies.java | 16 +- .../com/auth0/{ => java}/core/Strategy.java | 6 +- .../java/com/auth0/{ => java}/core/Token.java | 40 +- .../auth0/{ => java}/core/UserIdentity.java | 56 +- .../auth0/{ => java}/core/UserProfile.java | 76 +-- .../main/java/com/auth0/java/util/Build.java | 11 + .../auth0/{ => java}/util/CheckHelper.java | 2 +- .../main/java/com/auth0/java/util/Log.java | 23 + .../com/auth0/api/ParameterBuilderTest.java | 139 ----- .../AuthenticationAPIClientTest.java | 589 ------------------ .../auth0/api/internal/BaseRequestTest.java | 124 ---- .../java/com/auth0/core/ApplicationTest.java | 97 --- .../test/java/com/auth0/core/Auth0Test.java | 116 ---- .../java/com/auth0/core/ConnectionTest.java | 135 ---- .../java/com/auth0/core/StrategiesTest.java | 27 - .../java/com/auth0/core/UserProfileTest.java | 128 ---- .../auth0/util/APIClientExceptionMatcher.java | 81 --- .../com/auth0/util/AuthenticationAPI.java | 174 ------ .../util/AuthenticationCallbackMatcher.java | 79 --- .../java/com/auth0/util/CallbackMatcher.java | 87 --- .../util/MockAuthenticationCallback.java | 76 --- .../java/com/auth0/util/MockBaseCallback.java | 63 -- .../util/MockRefreshIdTokenCallback.java | 36 -- 51 files changed, 229 insertions(+), 2945 deletions(-) delete mode 100644 core/src/main/java/com/auth0/api/APIClient.java delete mode 100644 core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java delete mode 100644 core/src/main/java/com/auth0/api/BaseAPIClient.java rename core/src/main/java/com/auth0/{ => java}/api/APIClientException.java (97%) rename core/src/main/java/com/auth0/{ => java}/api/AuthorizableRequest.java (94%) rename core/src/main/java/com/auth0/{ => java}/api/ParameterBuilder.java (72%) rename core/src/main/java/com/auth0/{ => java}/api/ParameterizableRequest.java (89%) rename core/src/main/java/com/auth0/{ => java}/api/Request.java (94%) rename core/src/main/java/com/auth0/{ => java}/api/RequestBodyBuildException.java (90%) rename core/src/main/java/com/auth0/{ => java}/api/authentication/AuthenticationAPIClient.java (90%) rename core/src/main/java/com/auth0/{ => java}/api/authentication/AuthenticationRequest.java (86%) rename core/src/main/java/com/auth0/{ => java}/api/authentication/DelegationRequest.java (90%) rename core/src/main/java/com/auth0/{ => java}/api/authentication/SignUpRequest.java (81%) rename core/src/main/java/com/auth0/{ => java}/api/callback/AuthenticationCallback.java (79%) rename core/src/main/java/com/auth0/{ => java}/api/callback/BaseCallback.java (87%) rename core/src/main/java/com/auth0/{ => java}/api/callback/Callback.java (87%) rename core/src/main/java/com/auth0/{ => java}/api/callback/RefreshIdTokenCallback.java (97%) rename core/src/main/java/com/auth0/{ => java}/api/internal/ApplicationInfoRequest.java (84%) rename core/src/main/java/com/auth0/{ => java}/api/internal/BaseRequest.java (79%) rename core/src/main/java/com/auth0/{ => java}/api/internal/JsonRequestBodyBuilder.java (95%) rename core/src/main/java/com/auth0/{ => java}/api/internal/RequestFactory.java (55%) rename core/src/main/java/com/auth0/{ => java}/api/internal/SimpleRequest.java (81%) rename core/src/main/java/com/auth0/{ => java}/api/internal/VoidRequest.java (88%) rename core/src/main/java/com/auth0/{ => java}/core/Application.java (95%) rename core/src/main/java/com/auth0/{ => java}/core/Auth0.java (86%) rename core/src/main/java/com/auth0/{ => java}/core/Connection.java (57%) rename core/src/main/java/com/auth0/{ => java}/core/DatabaseUser.java (98%) rename core/src/main/java/com/auth0/{ => java}/core/Strategies.java (85%) rename core/src/main/java/com/auth0/{ => java}/core/Strategy.java (89%) rename core/src/main/java/com/auth0/{ => java}/core/Token.java (50%) rename core/src/main/java/com/auth0/{ => java}/core/UserIdentity.java (64%) rename core/src/main/java/com/auth0/{ => java}/core/UserProfile.java (54%) create mode 100644 core/src/main/java/com/auth0/java/util/Build.java rename core/src/main/java/com/auth0/{ => java}/util/CheckHelper.java (98%) create mode 100644 core/src/main/java/com/auth0/java/util/Log.java delete mode 100644 core/src/test/java/com/auth0/api/ParameterBuilderTest.java delete mode 100644 core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java delete mode 100644 core/src/test/java/com/auth0/api/internal/BaseRequestTest.java delete mode 100644 core/src/test/java/com/auth0/core/ApplicationTest.java delete mode 100644 core/src/test/java/com/auth0/core/Auth0Test.java delete mode 100644 core/src/test/java/com/auth0/core/ConnectionTest.java delete mode 100644 core/src/test/java/com/auth0/core/StrategiesTest.java delete mode 100644 core/src/test/java/com/auth0/core/UserProfileTest.java delete mode 100644 core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java delete mode 100644 core/src/test/java/com/auth0/util/AuthenticationAPI.java delete mode 100644 core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java delete mode 100644 core/src/test/java/com/auth0/util/CallbackMatcher.java delete mode 100644 core/src/test/java/com/auth0/util/MockAuthenticationCallback.java delete mode 100644 core/src/test/java/com/auth0/util/MockBaseCallback.java delete mode 100644 core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java diff --git a/core/build.gradle b/core/build.gradle index 821b426d..5a26087f 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -5,6 +5,7 @@ dependencies { compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1' compile 'com.fasterxml.jackson.core:jackson-core:2.4.1' compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.1' + compile 'org.json:json:20151123' testCompile 'junit:junit:4.12' } diff --git a/core/src/main/java/com/auth0/api/APIClient.java b/core/src/main/java/com/auth0/api/APIClient.java deleted file mode 100644 index 14ee3a62..00000000 --- a/core/src/main/java/com/auth0/api/APIClient.java +++ /dev/null @@ -1,368 +0,0 @@ -package com.auth0.api; - -import com.auth0.api.authentication.AuthenticationAPIClient; -import com.auth0.api.callback.AuthenticationCallback; -import com.auth0.api.callback.BaseCallback; -import com.auth0.api.callback.RefreshIdTokenCallback; -import com.auth0.core.Application; -import com.auth0.core.Auth0; -import com.auth0.core.Connection; -import com.auth0.core.DatabaseUser; -import com.auth0.core.Strategy; -import com.auth0.core.UserProfile; - -import java.util.HashMap; -import java.util.Map; - -/** - * API client for Auth0 Authentication API. - * @see Auth API docs - * @deprecated Use {@link AuthenticationAPIClient} - */ -@Deprecated -@SuppressWarnings("all") -public class APIClient extends BaseAPIClient { - - private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; - - private Application application; - private AuthenticationAPIClient newClient; - - /** - * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). - * @param clientID Your application clientID. - * @param baseURL Auth0's auth API endpoint - * @param configurationURL Auth0's enpoint where App info can be retrieved. - * @param tenantName Name of the tenant. Can be null - */ - public APIClient(String clientID, String baseURL, String configurationURL, String tenantName) { - super(clientID, baseURL, configurationURL, tenantName); - this.newClient = new AuthenticationAPIClient(new Auth0(clientID, baseURL, configurationURL)); - } - - /** - * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). - * @param clientID Your application clientID. - * @param baseURL Auth0's auth API endpoint - * @param configurationURL Auth0's enpoint where App info can be retrieved. - */ - public APIClient(String clientID, String baseURL, String configurationURL) { - this(clientID, baseURL, configurationURL, null); - } - - /** - * Creates a new API client using clientID and tenant name. - * @param clientID Your application clientID. - * @param tenantName Name of the tenant. - * @deprecated since 1.7.0, instead build using clientID and baseURL - */ - public APIClient(String clientID, String tenantName) { - super(clientID, tenantName); - this.newClient = new AuthenticationAPIClient(new Auth0(clientID, getBaseURL())); - } - - /** - * Fetch application information from {@link #getConfigurationURL()} - * @param callback called with the application info on success or with the failure reason. - */ - public void fetchApplicationInfo(final BaseCallback callback) { - newClient.fetchApplicationInfo() - .start(new BaseCallback() { - @Override - public void onSuccess(Application payload) { - callback.onSuccess(payload); - application = payload; - } - - @Override - public void onFailure(Throwable error) { - callback.onFailure(error); - } - }); - } - - /** - * Performs a Database connection login with username/email and password. - * @param username email or username required to login. By default it should be an email - * @param password user's password - * @param parameters additional parameters sent to the API like 'scope' - * @param callback called with User's profile and tokens or failure reason - */ - public void login(final String username, String password, Map parameters, final AuthenticationCallback callback) { - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .setClientId(getClientID()) - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - - newClient - .login(username, password) - .addParameters(request) - .start(callback); - } - - /** - * Performs a Social connection login using Identity Provider (IdP) credentials. - * @param connectionName name of the social connection - * @param accessToken accessToken from the IdP. - * @param parameters additional parameters sent to the API like 'scope' - * @param callback called with User's profile and tokens or failure reason - */ - public void socialLogin(final String connectionName, String accessToken, Map parameters, final AuthenticationCallback callback) { - Map params = parameters != null ? new HashMap<>(parameters) : new HashMap(); - if (params.containsKey("access_token")) { - params.put("main_access_token", params.remove("access_token")); - } - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .addAll(params) - .asDictionary(); - - newClient - .loginWithOAuthAccessToken(accessToken, connectionName) - .addParameters(request) - .start(callback); - } - - /** - * Performs a SMS connection login with a phone number and verification code. - * @param phoneNumber number where the verificationCode was received. - * @param verificationCode received by SMS. - * @param parameters additional parameters sent to the API like 'scope' - * @param callback called with User's profile and tokens or failure reason - */ - public void smsLogin(String phoneNumber, String verificationCode, Map parameters, final AuthenticationCallback callback) { - newClient.loginWithPhoneNumber(phoneNumber, verificationCode) - .addParameters(parameters) - .start(callback); - } - - /** - * Performs an Email connection login with an email and verification code. - * @param email where the user received the verificationCode - * @param verificationCode sent by email - * @param parameters to be sent for authentication in the request, useful to add extra values to Auth0 or override defaults - * @param callback called with user's profile and tokens, or failure reason - */ - public void emailLogin(String email, String verificationCode, Map parameters, final AuthenticationCallback callback) { - newClient.loginWithEmail(email, verificationCode) - .addParameters(parameters) - .start(callback); - } - - /** - * Creates and logs in a new User using a Database connection. - * @param email new user email - * @param username new user username - * @param password new user password - * @param parameters additional parameters additional parameters sent to the API like 'scope' - * @param callback called with User's profile and tokens or failure reason - */ - public void signUp(final String email, final String username, final String password, final Map parameters, final AuthenticationCallback callback) { - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - newClient.signUp(email, password, username) - .addSignUpParameters(request) - .addAuthenticationParameters(request) - .start(callback); - } - - /** - * Creates and logs in a new User using a Database connection. - * @param email new user email - * @param password new user password - * @param parameters additional parameters additional parameters sent to the API like 'scope' - * @param callback called with User's profile and tokens or failure reason - */ - public void signUp(final String email, final String password, final Map parameters, final AuthenticationCallback callback) { - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - newClient.signUp(email, password) - .addSignUpParameters(request) - .addAuthenticationParameters(parameters) - .start(callback); - } - - /** - * Creates a new user using a Database connection - * @param email new user email - * @param username new user username - * @param password new user password - * @param parameters additional parameters additional parameters sent to the API like 'scope' - * @param callback callback that will notify if the user was successfully created or not. - */ - public void createUser(final String email, final String username, final String password, final Map parameters, final BaseCallback callback) { - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - newClient.createUser(email, password, username) - .addParameters(request) - .start(new BaseCallback() { - @Override - public void onSuccess(DatabaseUser payload) { - callback.onSuccess(null); - } - - @Override - public void onFailure(Throwable error) { - callback.onFailure(error); - } - }); - } - - /** - * Creates a new user using a Database connection - * @param email new user email - * @param password new user password - * @param parameters additional parameters additional parameters sent to the API like 'scope' - * @param callback callback that will notify if the user was successfully created or not. - */ - public void createUser(final String email, final String password, final Map parameters, final BaseCallback callback) { - Map request = com.auth0.api.ParameterBuilder.newBuilder() - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - newClient.createUser(email, password) - .addParameters(request) - .start(new BaseCallback() { - @Override - public void onSuccess(DatabaseUser payload) { - callback.onSuccess(null); - } - - @Override - public void onFailure(Throwable error) { - callback.onFailure(error); - } - }); - } - - /** - * Request a change for the user's password using a Database connection. - * @param email user's email - * @param newPassword new password for the user - * @param parameters additional parameters additional parameters sent to the API like 'scope' - * @param callback callback that will notify if the user password request was sent or not. - */ - public void changePassword(final String email, String newPassword, Map parameters, BaseCallback callback) { - Map request = ParameterBuilder.newBuilder() - .setConnection(getDBConnectionName()) - .addAll(parameters) - .asDictionary(); - newClient.changePassword(email, newPassword) - .addParameters(request) - .start(callback); - } - - /** - * Fetches the user's profile with a valid 'id_token' - * @param idToken a JWT token associated to the user. - * @param callback called with the user's profile on success or with the failure reason - */ - public void fetchUserProfile(String idToken, final BaseCallback callback) { - newClient.tokenInfo(idToken) - .start(callback); - } - - /** - * Obtains a new id_token from Auth0 using another valid id_token - * @param idToken user's id_token - * @param parameters delegation api parameters - * @param callback called with new token in success or with the failure reason on error - */ - public void fetchIdTokenWithIdToken(String idToken, Map parameters, final RefreshIdTokenCallback callback) { - newClient.delegationWithIdToken(idToken) - .addParameters(parameters) - .start(callback); - } - - /** - * Obtains a new id_token from Auth0 using a refresh_token obtained on login when the scope has 'offline_access' - * @param refreshToken user's refresh token - * @param parameters delegation api parameters - * @param callback called with new token in success or with the failure reason on error - */ - public void fetchIdTokenWithRefreshToken(String refreshToken, Map parameters, final RefreshIdTokenCallback callback) { - newClient.delegationWithRefreshToken(refreshToken) - .addParameters(parameters) - .start(callback); - } - - /** - * Calls Auth0 delegation API to perform a delegated authentication, e.g. fetch Firebase or AWS tokens to call their API. - * The response of this API call will return a different response based on 'api_type' parameters, that's why the callback only returns a {@link Map}. - * @param parameters delegation api parameters - * @param callback called with delegation api response in success or with the failure reason on error. - */ - public void fetchDelegationToken(Map parameters, final BaseCallback> callback) { - newClient.delegation() - .addParameters(parameters) - .start(callback); - } - - /** - * Remove an account from another accounts identities. - * @param userId Id of the user account to remove, e.g.: if its a facebook account it will be 'facebook|fb_user_id'. - * @param accessToken Access token of the account that owns the account to unlink - * @param callback to call on either success or failure. - */ - public void unlinkAccount(String userId, String accessToken, final BaseCallback callback) { - newClient.unlink(userId, accessToken) - .start(callback); - } - - /** - * Start passwordless authentication flow calling "/passwordless/start" API. - * @param parameters sent to API to start the flow - * @param callback to call on either success or failure - */ - public void startPasswordless(Map parameters, final BaseCallback callback) { - newClient.passwordless() - .addParameters(parameters) - .start(callback); - } - - /** - * Request a verification code to login to be sent via SMS - * @param phoneNumber where the code is sent - * @param callback to call on either success or failure - */ - public void requestSMSVerificationCode(String phoneNumber, final BaseCallback callback) { - newClient.passwordlessWithSMS(phoneNumber, false) - .start(callback); - } - - /** - * Request a verification code to login to be sent via email - * @param email where the code is sent - * @param callback to call on either success or failure - */ - public void requestEmailVerificationCode(String email, final BaseCallback callback) { - newClient.passwordlessWithEmail(email, false) - .start(callback); - } - - /** - * Starts passwordless authentication with SMS, this will send a One Time Password to the user's phone via SMS - * @param phoneNumber to where the SMS one time password will be sent - * @param callback to call on either success or failure - * @deprecated in favor of generic {@link #startPasswordless(Map, BaseCallback)} or more specific ones {@link #requestSMSVerificationCode(String, BaseCallback)} and {@link #requestEmailVerificationCode(String, BaseCallback)} - */ - public void startPasswordless(String phoneNumber, final BaseCallback callback) { - requestSMSVerificationCode(phoneNumber, callback); - } - - private String getDBConnectionName() { - if (this.application == null || this.application.getDatabaseStrategy() == null) { - return DEFAULT_DB_CONNECTION; - } - Strategy strategy = this.application.getDatabaseStrategy(); - Connection db = strategy.getConnections().get(0); - return db.getName(); - } - -} diff --git a/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java b/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java deleted file mode 100644 index 8a00ebfb..00000000 --- a/core/src/main/java/com/auth0/api/AuthenticatedAPIClient.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * AuthenticatedAPIClient.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.api; - -import android.os.Handler; -import android.os.Looper; -import android.util.Log; - -import com.auth0.api.callback.BaseCallback; -import com.auth0.api.internal.RequestFactory; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.squareup.okhttp.HttpUrl; -import com.squareup.okhttp.OkHttpClient; - -import java.util.Map; - -/** - * API client for Auth0 API v2. - * @see API v2 docs - * @deprecated To request a SMS message for passwordless use {@link com.auth0.api.authentication.AuthenticationAPIClient} - */ -@Deprecated -@SuppressWarnings("all") -public class AuthenticatedAPIClient extends BaseAPIClient { - - private static final String TAG = AuthenticatedAPIClient.class.getName(); - - private String jwt; - private OkHttpClient newClient = new OkHttpClient(); - - /** - * Creates a new API client instance providing API and Configuration Urls different than the default. (Useful for on premise deploys). - * @param clientID Your application clientID. - * @param baseURL Auth0's API endpoint - * @param configurationURL Auth0's enpoint where App info can be retrieved. - * @param tenantName Name of the tenant. Can be null - */ - public AuthenticatedAPIClient(String clientID, String baseURL, String configurationURL, String tenantName) { - super(clientID, baseURL, configurationURL, tenantName); - } - - /** - * Creates a new API client instance providing API and Configuration Urls different than the default. (Useful for on premise deploys). - * @param clientID Your application clientID. - * @param baseURL Auth0's API endpoint - * @param configurationURL Auth0's endpoint where App info can be retrieved. - */ - public AuthenticatedAPIClient(String clientID, String baseURL, String configurationURL) { - super(clientID, baseURL, configurationURL); - } - - /** - * Creates a new API client using clientID and tenant name. - * @param clientID Your application clientID. - * @param tenantName Name of the tenant. - */ - public AuthenticatedAPIClient(String clientID, String tenantName) { - super(clientID, tenantName); - } - - /** - * Adds the header 'Authorization' with a given JWT token. - * @param jwt a valid JWT token - */ - public void setJWT(String jwt) { - this.jwt = jwt; - } - - /** - * Creates a user and request a SMS code using a configured SMS connection - * @param phoneNumber phone number that will receive the SMS code. - * @param callback callback when the SMS is sent or with the failure reason. - * @deprecated Use passwordless endpoints from {@link APIClient} - */ - public void requestSmsCode(String phoneNumber, final BaseCallback callback) { - HttpUrl url = HttpUrl.parse(getBaseURL()).newBuilder() - .addPathSegment("api") - .addPathSegment("v2") - .addPathSegment("users") - .build(); - Map params = ParameterBuilder.newBuilder() - .clearAll() - .setConnection("sms") - .set("email_verified", false) - .set("phone_number", phoneNumber) - .asDictionary(); - - Log.v(TAG, "Requesting SMS code for phone " + phoneNumber); - - RequestFactory.POST(url, newClient, new Handler(Looper.getMainLooper()), new ObjectMapper(), jwt) - .addParameters(params) - .start(callback); - } -} diff --git a/core/src/main/java/com/auth0/api/BaseAPIClient.java b/core/src/main/java/com/auth0/api/BaseAPIClient.java deleted file mode 100644 index 53767bcd..00000000 --- a/core/src/main/java/com/auth0/api/BaseAPIClient.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * BaseAPIClient.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.api; - -import android.net.Uri; - -import com.auth0.api.internal.RequestFactory; - -@Deprecated -abstract class BaseAPIClient { - - public static final String BASE_URL_FORMAT = "https://%s.auth0.com"; - public static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; - public static final String AUTH0_EU_CDN_URL = "https://cdn.eu.auth0.com"; - - private final String clientID; - private final String configurationURL; - private final String baseURL; - - public BaseAPIClient(String clientID, String baseURL, String configurationURL, String tenantName) { - this.clientID = clientID; - this.configurationURL = Uri.parse(configurationURL).buildUpon() - .appendPath("client") - .appendPath(this.clientID + ".js") - .build().toString(); - this.baseURL = baseURL; - } - - public BaseAPIClient(String clientID, String baseURL, String configurationURL) { - this(clientID, baseURL, configurationURL, null); - } - - @Deprecated - public BaseAPIClient(String clientID, String tenantName) { - this(clientID, String.format(BASE_URL_FORMAT, tenantName), AUTH0_US_CDN_URL, tenantName); - } - - public String getClientID() { - return clientID; - } - - public String getBaseURL() { - return baseURL; - } - - public String getConfigurationURL() { - return configurationURL; - } - - public void setClientInfo(String clientInfo) { - RequestFactory.setClientInfo(clientInfo); - } -} diff --git a/core/src/main/java/com/auth0/api/APIClientException.java b/core/src/main/java/com/auth0/java/api/APIClientException.java similarity index 97% rename from core/src/main/java/com/auth0/api/APIClientException.java rename to core/src/main/java/com/auth0/java/api/APIClientException.java index 991c057f..81e5d4e1 100644 --- a/core/src/main/java/com/auth0/api/APIClientException.java +++ b/core/src/main/java/com/auth0/java/api/APIClientException.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.api; +package com.auth0.java.api; import java.util.HashMap; import java.util.Map; @@ -44,7 +44,7 @@ public class APIClientException extends RuntimeException { public APIClientException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); this.statusCode = -1; - this.responseError = new HashMap(); + this.responseError = new HashMap<>(); } /** diff --git a/core/src/main/java/com/auth0/api/AuthorizableRequest.java b/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java similarity index 94% rename from core/src/main/java/com/auth0/api/AuthorizableRequest.java rename to core/src/main/java/com/auth0/java/api/AuthorizableRequest.java index e0af82ff..33b2586c 100644 --- a/core/src/main/java/com/auth0/api/AuthorizableRequest.java +++ b/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.api; +package com.auth0.java.api; /** * Interface for a Auth0 request that need Authorization using a JWT @@ -35,6 +35,6 @@ public interface AuthorizableRequest extends ParameterizableRequest { * @param jwt token to send to the API * @return itself */ - com.auth0.api.AuthorizableRequest setBearer(String jwt); + AuthorizableRequest setBearer(String jwt); } diff --git a/core/src/main/java/com/auth0/api/ParameterBuilder.java b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java similarity index 72% rename from core/src/main/java/com/auth0/api/ParameterBuilder.java rename to core/src/main/java/com/auth0/java/api/ParameterBuilder.java index cec16a0e..6a4c7b7b 100644 --- a/core/src/main/java/com/auth0/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java @@ -1,12 +1,11 @@ -package com.auth0.api; +package com.auth0.java.api; -import android.os.Build; +import com.auth0.java.util.Build; +import com.auth0.java.util.CheckHelper; import java.util.HashMap; import java.util.Map; -import static com.auth0.util.CheckHelper.checkArgument; - /** * Builder class for Auth API parameters. */ @@ -35,7 +34,7 @@ public ParameterBuilder() { * @param parameters default parameters */ public ParameterBuilder(Map parameters) { - checkArgument(parameters != null, "Must provide non-null parameters"); + CheckHelper.checkArgument(parameters != null, "Must provide non-null parameters"); this.parameters = new HashMap<>(parameters); } @@ -44,7 +43,7 @@ public ParameterBuilder(Map parameters) { * @param clientId clientID * @return itself */ - public com.auth0.api.ParameterBuilder setClientId(String clientId) { + public ParameterBuilder setClientId(String clientId) { return set("client_id", clientId); } @@ -53,7 +52,7 @@ public com.auth0.api.ParameterBuilder setClientId(String clientId) { * @param grantType grant type * @return itself */ - public com.auth0.api.ParameterBuilder setGrantType(String grantType) { + public ParameterBuilder setGrantType(String grantType) { return set("grant_type", grantType); } @@ -62,7 +61,7 @@ public com.auth0.api.ParameterBuilder setGrantType(String grantType) { * @param connection name of the connection * @return itself */ - public com.auth0.api.ParameterBuilder setConnection(String connection) { + public ParameterBuilder setConnection(String connection) { return set(CONNECTION, connection); } @@ -71,7 +70,7 @@ public com.auth0.api.ParameterBuilder setConnection(String connection) { * @param scope a scope value * @return itself */ - public com.auth0.api.ParameterBuilder setScope(String scope) { + public ParameterBuilder setScope(String scope) { if (scope.contains("offline_access")) { setDevice(Build.MODEL); } else { @@ -85,7 +84,7 @@ public com.auth0.api.ParameterBuilder setScope(String scope) { * @param device a device name * @return itself */ - public com.auth0.api.ParameterBuilder setDevice(String device) { + public ParameterBuilder setDevice(String device) { return set("device", device); } @@ -94,7 +93,7 @@ public com.auth0.api.ParameterBuilder setDevice(String device) { * @param accessToken a access token * @return itself */ - public com.auth0.api.ParameterBuilder setAccessToken(String accessToken) { + public ParameterBuilder setAccessToken(String accessToken) { return set(ACCESS_TOKEN, accessToken); } @@ -104,7 +103,7 @@ public com.auth0.api.ParameterBuilder setAccessToken(String accessToken) { * @param value parameter value * @return itself */ - public com.auth0.api.ParameterBuilder set(String key, Object value) { + public ParameterBuilder set(String key, Object value) { this.parameters.put(key, value); return this; } @@ -114,7 +113,7 @@ public com.auth0.api.ParameterBuilder set(String key, Object value) { * @param parameters map with parameters to add * @return itself */ - public com.auth0.api.ParameterBuilder addAll(Map parameters) { + public ParameterBuilder addAll(Map parameters) { if (parameters != null) { this.parameters.putAll(parameters); } @@ -125,7 +124,7 @@ public com.auth0.api.ParameterBuilder addAll(Map parameters) { * Clears all existing parameters * @return itself */ - public com.auth0.api.ParameterBuilder clearAll() { + public ParameterBuilder clearAll() { parameters.clear(); return this; } @@ -142,16 +141,16 @@ public Map asDictionary() { * Creates a new instance of the builder with default values * @return a new builder */ - public static com.auth0.api.ParameterBuilder newBuilder() { - return new com.auth0.api.ParameterBuilder(); + public static ParameterBuilder newBuilder() { + return new ParameterBuilder(); } /** * Creates a new instance of the builder without any default values * @return a new builder */ - public static com.auth0.api.ParameterBuilder newEmptyBuilder() { - return new com.auth0.api.ParameterBuilder(new HashMap()); + public static ParameterBuilder newEmptyBuilder() { + return new ParameterBuilder(new HashMap()); } /** @@ -159,8 +158,8 @@ public static com.auth0.api.ParameterBuilder newEmptyBuilder() { * @param parameters default parameters * @return a new builder */ - public static com.auth0.api.ParameterBuilder newBuilder(Map parameters) { - return new com.auth0.api.ParameterBuilder(parameters); + public static ParameterBuilder newBuilder(Map parameters) { + return new ParameterBuilder(parameters); } } diff --git a/core/src/main/java/com/auth0/api/ParameterizableRequest.java b/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java similarity index 89% rename from core/src/main/java/com/auth0/api/ParameterizableRequest.java rename to core/src/main/java/com/auth0/java/api/ParameterizableRequest.java index 9e3880ab..de9fb199 100644 --- a/core/src/main/java/com/auth0/api/ParameterizableRequest.java +++ b/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.api; +package com.auth0.java.api; import java.util.Map; @@ -37,7 +37,7 @@ public interface ParameterizableRequest extends Request { * @param parameters as a non-null dictionary * @return itself */ - com.auth0.api.ParameterizableRequest addParameters(Map parameters); + ParameterizableRequest addParameters(Map parameters); /** * Adds an additional header for the request @@ -45,6 +45,6 @@ public interface ParameterizableRequest extends Request { * @param value of the header * @return itself */ - com.auth0.api.ParameterizableRequest addHeader(String name, String value); + ParameterizableRequest addHeader(String name, String value); } diff --git a/core/src/main/java/com/auth0/api/Request.java b/core/src/main/java/com/auth0/java/api/Request.java similarity index 94% rename from core/src/main/java/com/auth0/api/Request.java rename to core/src/main/java/com/auth0/java/api/Request.java index 602ea96e..5f91b376 100644 --- a/core/src/main/java/com/auth0/api/Request.java +++ b/core/src/main/java/com/auth0/java/api/Request.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.api; +package com.auth0.java.api; -import com.auth0.api.callback.BaseCallback; +import com.auth0.java.api.callback.BaseCallback; /** * Defines a request that can be started diff --git a/core/src/main/java/com/auth0/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java similarity index 90% rename from core/src/main/java/com/auth0/api/RequestBodyBuildException.java rename to core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java index 18c94c6b..43a81c14 100644 --- a/core/src/main/java/com/auth0/api/RequestBodyBuildException.java +++ b/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java @@ -1,4 +1,4 @@ -package com.auth0.api; +package com.auth0.java.api; /** * Exception that wraps errors when creating a body for a request diff --git a/core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java similarity index 90% rename from core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java rename to core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java index 4ad2f6d3..c1303588 100644 --- a/core/src/main/java/com/auth0/api/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java @@ -22,28 +22,25 @@ * THE SOFTWARE. */ -package com.auth0.api.authentication; - -import android.os.Handler; -import android.os.Looper; -import android.util.Log; - -import com.auth0.api.ParameterBuilder; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.Request; -import com.auth0.api.internal.RequestFactory; -import com.auth0.core.Application; -import com.auth0.core.Auth0; -import com.auth0.core.DatabaseUser; -import com.auth0.core.Token; -import com.auth0.core.UserProfile; +package com.auth0.java.api.authentication; + +import com.auth0.java.api.ParameterBuilder; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.Request; +import com.auth0.java.api.internal.RequestFactory; +import com.auth0.java.core.Application; +import com.auth0.java.core.Auth0; +import com.auth0.java.core.DatabaseUser; +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; +import com.auth0.java.util.Log; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; import java.util.Map; -import static com.auth0.api.ParameterBuilder.GRANT_TYPE_PASSWORD; +import static com.auth0.java.api.ParameterBuilder.GRANT_TYPE_PASSWORD; /** * API client for Auth0 Authentication API. @@ -51,7 +48,7 @@ */ public class AuthenticationAPIClient { - private static final String TAG = com.auth0.api.authentication.AuthenticationAPIClient.class.getName(); + private static final String TAG = AuthenticationAPIClient.class.getName(); private static final String USERNAME_KEY = "username"; private static final String PASSWORD_KEY = "password"; @@ -65,7 +62,6 @@ public class AuthenticationAPIClient { private final Auth0 auth0; private final OkHttpClient client; - private final Handler handler; private final ObjectMapper mapper; private String defaultDbConnection = DEFAULT_DB_CONNECTION; @@ -75,16 +71,7 @@ public class AuthenticationAPIClient { * @param auth0 account information */ public AuthenticationAPIClient(Auth0 auth0) { - this(auth0, new Handler(Looper.getMainLooper())); - } - - /** - * Creates a new API client instance providing Auth0 account info and a handler where all callbacks will be called - * @param auth0 account information - * @param handler where callback will be called with either the response or error from the server - */ - public AuthenticationAPIClient(Auth0 auth0, Handler handler) { - this(auth0, new OkHttpClient(), handler, new ObjectMapper()); + this(auth0, new OkHttpClient(), new ObjectMapper()); } /** @@ -98,10 +85,9 @@ public AuthenticationAPIClient(String clientID, String baseURL, String configura this(new Auth0(clientID, baseURL, configurationURL)); } - AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, Handler handler, ObjectMapper mapper) { + AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { this.auth0 = auth0; this.client = client; - this.handler = handler; this.mapper = mapper; } @@ -130,7 +116,7 @@ public Request fetchApplicationInfo() { .addPathSegment("client") .addPathSegment(auth0.getClientId() + ".js") .build(); - return RequestFactory.newApplicationInfoRequest(url, client, handler, mapper); + return RequestFactory.newApplicationInfoRequest(url, client, mapper); } /** @@ -147,7 +133,7 @@ public ParameterizableRequest loginWithResourceOwner() { .setClientId(getClientId()) .setConnection(defaultDbConnection) .asDictionary(); - ParameterizableRequest request = RequestFactory.POST(url, client, handler, mapper, Token.class) + ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) .addParameters(requestParameters); Log.d(TAG, "Trying to login using " + url.toString() + " with parameters " + requestParameters); return request; @@ -189,7 +175,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn Log.v(TAG, "Performing OAuth access_token login with parameters " + parameters); final ParameterizableRequest profileRequest = profileRequest(); - ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, handler, mapper, Token.class) + ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, mapper, Token.class) .addParameters(parameters); return new AuthenticationRequest(credentialsRequest, profileRequest); } @@ -263,7 +249,7 @@ public ParameterizableRequest createUser(String email, String pass .setClientId(getClientId()) .asDictionary(); Log.d(TAG, "Creating user with email " + email + " and username " + username); - return RequestFactory.POST(url, client, handler, mapper, DatabaseUser.class) + return RequestFactory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); } @@ -285,10 +271,10 @@ public ParameterizableRequest createUser(String email, String pass * @param username of the user and must be non null * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public com.auth0.api.authentication.SignUpRequest signUp(String email, String password, String username) { + public SignUpRequest signUp(String email, String password, String username) { ParameterizableRequest createUserRequest = createUser(email, password, username); AuthenticationRequest authenticationRequest = login(email, password); - return new com.auth0.api.authentication.SignUpRequest(createUserRequest, authenticationRequest); + return new SignUpRequest(createUserRequest, authenticationRequest); } /** @@ -298,7 +284,7 @@ public com.auth0.api.authentication.SignUpRequest signUp(String email, String pa * @param password of the user and must be non null * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public com.auth0.api.authentication.SignUpRequest signUp(String email, String password) { + public SignUpRequest signUp(String email, String password) { ParameterizableRequest createUserRequest = createUser(email, password); AuthenticationRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); @@ -323,7 +309,7 @@ public ParameterizableRequest changePassword(String email, String newPassw .setConnection(defaultDbConnection) .asDictionary(); - return RequestFactory.POST(url, client, handler, mapper) + return RequestFactory.POST(url, client, mapper) .addParameters(parameters); } @@ -340,7 +326,7 @@ public ParameterizableRequest> delegation() { .setClientId(getClientId()) .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) .asDictionary(); - return RequestFactory.rawPOST(url, client, handler, mapper) + return RequestFactory.rawPOST(url, client, mapper) .addParameters(parameters); } @@ -393,7 +379,7 @@ public Request unlink(String userId, String accessToken) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("unlink") .build(); - return RequestFactory.POST(url, client, handler, mapper) + return RequestFactory.POST(url, client, mapper) .addParameters(parameters); } @@ -412,7 +398,7 @@ public ParameterizableRequest passwordless() { .setClientId(getClientId()) .asDictionary(); - return RequestFactory.POST(url, client, handler, mapper) + return RequestFactory.POST(url, client, mapper) .addParameters(parameters); } @@ -454,7 +440,7 @@ private ParameterizableRequest profileRequest() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("tokeninfo") .build(); - return RequestFactory.POST(url, client, handler, mapper, UserProfile.class); + return RequestFactory.POST(url, client, mapper, UserProfile.class); } diff --git a/core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java similarity index 86% rename from core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java rename to core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java index 20ddd4eb..96b5ccde 100644 --- a/core/src/main/java/com/auth0/api/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java @@ -22,14 +22,14 @@ * THE SOFTWARE. */ -package com.auth0.api.authentication; +package com.auth0.java.api.authentication; -import com.auth0.api.ParameterBuilder; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.callback.AuthenticationCallback; -import com.auth0.api.callback.BaseCallback; -import com.auth0.core.Token; -import com.auth0.core.UserProfile; +import com.auth0.java.api.ParameterBuilder; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.callback.AuthenticationCallback; +import com.auth0.java.api.callback.BaseCallback; +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; import java.util.Map; @@ -51,7 +51,7 @@ public class AuthenticationRequest { * @param parameters as a non-null dictionary * @return itself */ - public com.auth0.api.authentication.AuthenticationRequest addParameters(Map parameters) { + public AuthenticationRequest addParameters(Map parameters) { credentialsRequest.addParameters(parameters); return this; } @@ -61,7 +61,7 @@ public com.auth0.api.authentication.AuthenticationRequest addParameters(Map parameters) { + public DelegationRequest addParameters(Map parameters) { request.addParameters(parameters); return this; } diff --git a/core/src/main/java/com/auth0/api/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java similarity index 81% rename from core/src/main/java/com/auth0/api/authentication/SignUpRequest.java rename to core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java index 443c2d85..9569b08b 100644 --- a/core/src/main/java/com/auth0/api/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.api.authentication; +package com.auth0.java.api.authentication; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.callback.AuthenticationCallback; -import com.auth0.api.callback.BaseCallback; -import com.auth0.core.DatabaseUser; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.callback.AuthenticationCallback; +import com.auth0.java.api.callback.BaseCallback; +import com.auth0.java.core.DatabaseUser; import java.util.Map; @@ -37,7 +37,7 @@ public class SignUpRequest { private final ParameterizableRequest signUpRequest; - private final com.auth0.api.authentication.AuthenticationRequest authenticationRequest; + private final AuthenticationRequest authenticationRequest; SignUpRequest(ParameterizableRequest signUpRequest, AuthenticationRequest authenticationRequest) { this.signUpRequest = signUpRequest; @@ -49,7 +49,7 @@ public class SignUpRequest { * @param parameters as a non-null dictionary * @return itself */ - public com.auth0.api.authentication.SignUpRequest addSignUpParameters(Map parameters) { + public SignUpRequest addSignUpParameters(Map parameters) { signUpRequest.addParameters(parameters); return this; } @@ -59,7 +59,7 @@ public com.auth0.api.authentication.SignUpRequest addSignUpParameters(Map parameters) { + public SignUpRequest addAuthenticationParameters(Map parameters) { authenticationRequest.addParameters(parameters); return this; } @@ -69,7 +69,7 @@ public com.auth0.api.authentication.SignUpRequest addAuthenticationParameters(Ma * @param scope value * @return itself */ - public com.auth0.api.authentication.SignUpRequest setScope(String scope) { + public SignUpRequest setScope(String scope) { authenticationRequest.setScope(scope); return this; } @@ -79,7 +79,7 @@ public com.auth0.api.authentication.SignUpRequest setScope(String scope) { * @param connection name * @return itself */ - public com.auth0.api.authentication.SignUpRequest setConnection(String connection) { + public SignUpRequest setConnection(String connection) { authenticationRequest.setConnection(connection); return this; } diff --git a/core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java b/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java similarity index 79% rename from core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java rename to core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java index 41b3f2e7..5698725d 100644 --- a/core/src/main/java/com/auth0/api/callback/AuthenticationCallback.java +++ b/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java @@ -1,7 +1,7 @@ -package com.auth0.api.callback; +package com.auth0.java.api.callback; -import com.auth0.core.Token; -import com.auth0.core.UserProfile; +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; /** * Callback for authentication API calls to Auth0 API. diff --git a/core/src/main/java/com/auth0/api/callback/BaseCallback.java b/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java similarity index 87% rename from core/src/main/java/com/auth0/api/callback/BaseCallback.java rename to core/src/main/java/com/auth0/java/api/callback/BaseCallback.java index b114ac56..d0fedc29 100644 --- a/core/src/main/java/com/auth0/api/callback/BaseCallback.java +++ b/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java @@ -1,4 +1,4 @@ -package com.auth0.api.callback; +package com.auth0.java.api.callback; /** * Callback that receives a single value on success. diff --git a/core/src/main/java/com/auth0/api/callback/Callback.java b/core/src/main/java/com/auth0/java/api/callback/Callback.java similarity index 87% rename from core/src/main/java/com/auth0/api/callback/Callback.java rename to core/src/main/java/com/auth0/java/api/callback/Callback.java index edcae44c..eb04de94 100644 --- a/core/src/main/java/com/auth0/api/callback/Callback.java +++ b/core/src/main/java/com/auth0/java/api/callback/Callback.java @@ -1,4 +1,4 @@ -package com.auth0.api.callback; +package com.auth0.java.api.callback; /** * Interface for all callbacks used with Auth0 API clients diff --git a/core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java b/core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java similarity index 97% rename from core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java rename to core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java index c7e030d0..1187f5ee 100644 --- a/core/src/main/java/com/auth0/api/callback/RefreshIdTokenCallback.java +++ b/core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.api.callback; +package com.auth0.java.api.callback; /** * Callback used in delegation api request for a new Auth0 id_token diff --git a/core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java similarity index 84% rename from core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java rename to core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java index 0ce908ee..a47c1aa0 100644 --- a/core/src/main/java/com/auth0/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java @@ -22,14 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; +package com.auth0.java.api.internal; -import android.os.Handler; -import android.util.Log; - -import com.auth0.api.APIClientException; -import com.auth0.api.ParameterizableRequest; -import com.auth0.core.Application; +import com.auth0.java.api.APIClientException; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.core.Application; +import com.auth0.java.util.Log; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; @@ -46,10 +44,10 @@ class ApplicationInfoRequest extends BaseRequest implements Callback { - private static final String TAG = com.auth0.api.internal.ApplicationInfoRequest.class.getName(); + private static final String TAG = ApplicationInfoRequest.class.getName(); - public ApplicationInfoRequest(Handler handler, OkHttpClient client, HttpUrl url, ObjectMapper mapper) { - super(handler, url, client, mapper.reader(Application.class), null); + public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper mapper) { + super(url, client, mapper.reader(Application.class), null); } @Override @@ -73,8 +71,9 @@ public void onResponse(Response response) throws IOException { } try { String json = response.body().string(); + json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method JSONTokener tokenizer = new JSONTokener(json); - tokenizer.skipPast("Auth0.setClient("); + //tokenizer.skipPast("Auth0.setClient("); if (!tokenizer.more()) { postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP")); return; diff --git a/core/src/main/java/com/auth0/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java similarity index 79% rename from core/src/main/java/com/auth0/api/internal/BaseRequest.java rename to core/src/main/java/com/auth0/java/api/internal/BaseRequest.java index 1d19d2ff..bec2b6d2 100644 --- a/core/src/main/java/com/auth0/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java @@ -22,17 +22,15 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; - -import android.os.Build; -import android.os.Handler; -import android.util.Log; - -import com.auth0.api.APIClientException; -import com.auth0.api.AuthorizableRequest; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.RequestBodyBuildException; -import com.auth0.api.callback.BaseCallback; +package com.auth0.java.api.internal; + +import com.auth0.java.api.APIClientException; +import com.auth0.java.api.AuthorizableRequest; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.RequestBodyBuildException; +import com.auth0.java.api.callback.BaseCallback; +import com.auth0.java.util.Build; +import com.auth0.java.util.Log; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; @@ -49,7 +47,6 @@ abstract class BaseRequest implements ParameterizableRequest, Authorizable private static final String TAG = BaseCallback.class.getName(); - private final Handler handler; private final Map headers; private final Map parameters; private final HttpUrl url; @@ -59,12 +56,11 @@ abstract class BaseRequest implements ParameterizableRequest, Authorizable private BaseCallback callback; - protected BaseRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer) { - this(handler, url, client, reader, writer, null); + protected BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer) { + this(url, client, reader, writer, null); } - public BaseRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer, BaseCallback callback) { - this.handler = handler; + public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer, BaseCallback callback) { this.url = url; this.client = client; this.reader = reader; @@ -80,22 +76,12 @@ protected void setCallback(BaseCallback callback) { } protected void postOnSuccess(final T payload) { - handler.post(new CallbackTask(callback) { - @Override - public void run() { - this.callback.onSuccess(payload); - } - }); + this.callback.onSuccess(payload); } protected final void postOnFailure(final Throwable error) { Log.e(TAG, "Failed to make request to " + url, error); - handler.post(new CallbackTask(callback) { - @Override - public void run() { - this.callback.onFailure(error); - } - }); + this.callback.onFailure(error); } protected Request.Builder newBuilder() { @@ -116,7 +102,7 @@ protected ObjectReader getReader() { } protected RequestBody buildBody() throws RequestBodyBuildException { - return com.auth0.api.internal.JsonRequestBodyBuilder.createBody(parameters, writer); + return JsonRequestBodyBuilder.createBody(parameters, writer); } private static abstract class CallbackTask implements Runnable { diff --git a/core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java b/core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java similarity index 95% rename from core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java rename to core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java index 1abf76ea..a131c126 100644 --- a/core/src/main/java/com/auth0/api/internal/JsonRequestBodyBuilder.java +++ b/core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; +package com.auth0.java.api.internal; -import com.auth0.api.RequestBodyBuildException; +import com.auth0.java.api.RequestBodyBuildException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.MediaType; diff --git a/core/src/main/java/com/auth0/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java similarity index 55% rename from core/src/main/java/com/auth0/api/internal/RequestFactory.java rename to core/src/main/java/com/auth0/java/api/internal/RequestFactory.java index 6bc11f60..96064139 100644 --- a/core/src/main/java/com/auth0/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java @@ -22,14 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; +package com.auth0.java.api.internal; -import android.os.Handler; - -import com.auth0.api.AuthorizableRequest; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.Request; -import com.auth0.core.Application; +import com.auth0.java.api.AuthorizableRequest; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.Request; +import com.auth0.java.core.Application; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -46,44 +44,44 @@ public static void setClientInfo(String clientInfo) { CLIENT_INFO = clientInfo; } - public static ParameterizableRequest GET(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "GET", clazz)); + public static ParameterizableRequest GET(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "POST", clazz)); + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new SimpleRequest<>(url, client, mapper, "POST", clazz)); } - public static ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { - final com.auth0.api.internal.SimpleRequest> request = new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "POST"); + public static ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + final SimpleRequest> request = new SimpleRequest<>(url, client, mapper, "POST"); addMetricHeader(request); return request; } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { - return addMetricHeader(new com.auth0.api.internal.VoidRequest(handler, url, client, mapper, "POST")); + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + return addMetricHeader(new VoidRequest(url, client, mapper, "POST")); } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, String jwt) { - final AuthorizableRequest request = new com.auth0.api.internal.VoidRequest(handler, url, client, mapper, "POST") + public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String jwt) { + final AuthorizableRequest request = new VoidRequest(url, client, mapper, "POST") .setBearer(jwt); return addMetricHeader(request); } - public static ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "PUT", clazz)); + public static ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new SimpleRequest<>(url, client, mapper, "PUT", clazz)); } - public static ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "GET", clazz)); + public static ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); } - public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new com.auth0.api.internal.SimpleRequest<>(handler, url, client, mapper, "DELETE", clazz)); + public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + return addMetricHeader(new SimpleRequest<>(url, client, mapper, "DELETE", clazz)); } - public static Request newApplicationInfoRequest(HttpUrl url, OkHttpClient client, Handler handler, ObjectMapper mapper) { - return addMetricHeader(new com.auth0.api.internal.ApplicationInfoRequest(handler, client, url, mapper)); + public static Request newApplicationInfoRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + return addMetricHeader(new ApplicationInfoRequest(client, url, mapper)); } private static ParameterizableRequest addMetricHeader(ParameterizableRequest request) { diff --git a/core/src/main/java/com/auth0/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java similarity index 81% rename from core/src/main/java/com/auth0/api/internal/SimpleRequest.java rename to core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java index 9a67bf9c..5efcd57a 100644 --- a/core/src/main/java/com/auth0/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java @@ -22,15 +22,13 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; +package com.auth0.java.api.internal; -import android.os.Handler; -import android.util.Log; - -import com.auth0.api.APIClientException; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.Request; -import com.auth0.api.RequestBodyBuildException; +import com.auth0.java.api.APIClientException; +import com.auth0.java.api.ParameterizableRequest; +import com.auth0.java.api.Request; +import com.auth0.java.api.RequestBodyBuildException; +import com.auth0.java.util.Log; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @@ -46,19 +44,19 @@ class SimpleRequest extends BaseRequest implements Request, ParameterizableRequest, Callback { - private static final String TAG = com.auth0.api.internal.SimpleRequest.class.getName(); + private static final String TAG = SimpleRequest.class.getName(); private final ObjectReader errorReader; private final String method; - public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { - super(handler, url, client, mapper.reader(clazz), mapper.writer()); + public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { + super(url, client, mapper.reader(clazz), mapper.writer()); this.errorReader = mapper.reader(new TypeReference>() {}); this.method = httpMethod; } - public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { - super(handler, url, client, mapper.reader(new TypeReference>() {}), mapper.writer()); + public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { + super(url, client, mapper.reader(new TypeReference>() {}), mapper.writer()); this.errorReader = mapper.reader(new TypeReference>() { }); this.method = httpMethod; diff --git a/core/src/main/java/com/auth0/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java similarity index 88% rename from core/src/main/java/com/auth0/api/internal/VoidRequest.java rename to core/src/main/java/com/auth0/java/api/internal/VoidRequest.java index 15e5e0b2..73d30b53 100644 --- a/core/src/main/java/com/auth0/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java @@ -22,12 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.api.internal; +package com.auth0.java.api.internal; -import android.os.Handler; -import android.util.Log; - -import com.auth0.api.APIClientException; +import com.auth0.java.api.APIClientException; +import com.auth0.java.util.Log; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @@ -43,13 +41,13 @@ class VoidRequest extends BaseRequest implements Callback { - private static final String TAG = com.auth0.api.internal.VoidRequest.class.getName(); + private static final String TAG = VoidRequest.class.getName(); private final ObjectReader errorReader; private final String httpMethod; - public VoidRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { - super(handler, url, client, null, mapper.writer()); + public VoidRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { + super(url, client, null, mapper.writer()); this.httpMethod = httpMethod; this.errorReader = mapper.reader(new TypeReference>() { }); diff --git a/core/src/main/java/com/auth0/core/Application.java b/core/src/main/java/com/auth0/java/core/Application.java similarity index 95% rename from core/src/main/java/com/auth0/core/Application.java rename to core/src/main/java/com/auth0/java/core/Application.java index 157dcf65..f9e0814b 100644 --- a/core/src/main/java/com/auth0/core/Application.java +++ b/core/src/main/java/com/auth0/java/core/Application.java @@ -1,4 +1,4 @@ -package com.auth0.core; +package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -7,7 +7,7 @@ import java.util.ArrayList; import java.util.List; -import static com.auth0.util.CheckHelper.checkArgument; +import static com.auth0.java.util.CheckHelper.checkArgument; /** * Class with your Auth0's application information and the list of enabled connections (DB, Social, Enterprise, Passwordless). @@ -154,9 +154,9 @@ public List getEnterpriseStrategies() { } /** - * Returns a {@link com.auth0.core.Strategy} by its name + * Returns a {@link Strategy} by its name * @param name strategy name - * @return a {@link com.auth0.core.Strategy} + * @return a {@link Strategy} */ public Strategy strategyForName(String name) { for (Strategy strategy: this.strategies) { @@ -170,7 +170,7 @@ public Strategy strategyForName(String name) { /** * Returns the strategy by one of its connections * @param connection a connection - * @return a {@link com.auth0.core.Strategy} + * @return a {@link Strategy} */ public Strategy strategyForConnection(Connection connection) { for (Strategy strategy: this.strategies) { diff --git a/core/src/main/java/com/auth0/core/Auth0.java b/core/src/main/java/com/auth0/java/core/Auth0.java similarity index 86% rename from core/src/main/java/com/auth0/core/Auth0.java rename to core/src/main/java/com/auth0/java/core/Auth0.java index 72275bae..05471611 100644 --- a/core/src/main/java/com/auth0/core/Auth0.java +++ b/core/src/main/java/com/auth0/java/core/Auth0.java @@ -22,12 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.core; +package com.auth0.java.core; -import android.net.Uri; - -import com.auth0.api.APIClient; -import com.auth0.api.authentication.AuthenticationAPIClient; +import com.auth0.java.api.authentication.AuthenticationAPIClient; +import com.squareup.okhttp.HttpUrl; public class Auth0 { @@ -51,8 +49,8 @@ public Auth0(String clientId, String domain, String configurationDomain) { private String resolveConfiguration(String configurationDomain, String domainUrl) { String url = ensureUrlString(configurationDomain); if (configurationDomain == null && domainUrl != null) { - final Uri domainUri = Uri.parse(domainUrl); - final String host = domainUri.getHost(); + final HttpUrl domainUri = HttpUrl.parse(domainUrl); + final String host = domainUri.host(); if (host.endsWith(DOT_AUTH0_DOT_COM)) { String[] parts = host.split("\\."); if (parts.length > 3) { @@ -87,18 +85,13 @@ public String getConfigurationUrl() { return configurationUrl; } - @Deprecated - public APIClient newAPIClient() { - return new APIClient(this.clientId, this.domainUrl, this.configurationUrl); - } - public AuthenticationAPIClient newAuthenticationAPIClient() { return new AuthenticationAPIClient(this); } public String getAuthorizeUrl() { - return Uri.parse(domainUrl).buildUpon() - .path("authorize") + return HttpUrl.parse(domainUrl).newBuilder() + .addEncodedPathSegment("authorize") .build() .toString(); } diff --git a/core/src/main/java/com/auth0/core/Connection.java b/core/src/main/java/com/auth0/java/core/Connection.java similarity index 57% rename from core/src/main/java/com/auth0/core/Connection.java rename to core/src/main/java/com/auth0/java/core/Connection.java index 97331b1d..14741109 100644 --- a/core/src/main/java/com/auth0/core/Connection.java +++ b/core/src/main/java/com/auth0/java/core/Connection.java @@ -1,24 +1,19 @@ -package com.auth0.core; - -import android.os.Parcel; -import android.os.Parcelable; +package com.auth0.java.core; +import com.auth0.java.util.CheckHelper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import static com.auth0.util.CheckHelper.checkArgument; - /** * Class with a Auth0 connection info */ @JsonIgnoreProperties(ignoreUnknown = true) -public class Connection implements Parcelable { +public class Connection { private String name; @@ -30,9 +25,9 @@ public class Connection implements Parcelable { */ @JsonCreator public Connection(Map values) { - checkArgument(values != null && values.size() > 0, "Must have at least one value"); + CheckHelper.checkArgument(values != null && values.size() > 0, "Must have at least one value"); final String name = (String) values.remove("name"); - checkArgument(name != null, "Must have a non-null name"); + CheckHelper.checkArgument(name != null, "Must have a non-null name"); this.name = name; this.values = values; } @@ -91,43 +86,4 @@ public Set getDomainSet() { } return domains; } - - @SuppressWarnings("unchecked") - protected Connection(Parcel in) { - name = in.readString(); - if (in.readByte() == 0x01) { - values = (Map) in.readSerializable(); - } else { - values = new HashMap<>(); - } - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(name); - if (values == null || values.isEmpty()) { - dest.writeByte((byte) 0x00); - } else { - dest.writeByte((byte) (0x01)); - dest.writeSerializable(new HashMap<>(values)); - } - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public com.auth0.core.Connection createFromParcel(Parcel in) { - return new com.auth0.core.Connection(in); - } - - @Override - public com.auth0.core.Connection[] newArray(int size) { - return new com.auth0.core.Connection[size]; - } - }; } diff --git a/core/src/main/java/com/auth0/core/DatabaseUser.java b/core/src/main/java/com/auth0/java/core/DatabaseUser.java similarity index 98% rename from core/src/main/java/com/auth0/core/DatabaseUser.java rename to core/src/main/java/com/auth0/java/core/DatabaseUser.java index d1ad8592..8738048d 100644 --- a/core/src/main/java/com/auth0/core/DatabaseUser.java +++ b/core/src/main/java/com/auth0/java/core/DatabaseUser.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.core; +package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/core/src/main/java/com/auth0/core/Strategies.java b/core/src/main/java/com/auth0/java/core/Strategies.java similarity index 85% rename from core/src/main/java/com/auth0/core/Strategies.java rename to core/src/main/java/com/auth0/java/core/Strategies.java index 34f18cf6..a7aff139 100644 --- a/core/src/main/java/com/auth0/core/Strategies.java +++ b/core/src/main/java/com/auth0/java/core/Strategies.java @@ -1,9 +1,9 @@ -package com.auth0.core; +package com.auth0.java.core; -import static com.auth0.core.Strategies.Type.DATABASE; -import static com.auth0.core.Strategies.Type.ENTERPRISE; -import static com.auth0.core.Strategies.Type.PASSWORDLESS; -import static com.auth0.core.Strategies.Type.SOCIAL; +import static com.auth0.java.core.Strategies.Type.DATABASE; +import static com.auth0.java.core.Strategies.Type.ENTERPRISE; +import static com.auth0.java.core.Strategies.Type.PASSWORDLESS; +import static com.auth0.java.core.Strategies.Type.SOCIAL; /** * An enum with all strategies available in Auth0 @@ -81,9 +81,9 @@ public Type getType() { return type; } - public static com.auth0.core.Strategies fromName(String name) { - com.auth0.core.Strategies strategy = null; - for (com.auth0.core.Strategies str: values()) { + public static Strategies fromName(String name) { + Strategies strategy = null; + for (Strategies str: values()) { if (str.getName().equals(name)) { strategy = str; break; diff --git a/core/src/main/java/com/auth0/core/Strategy.java b/core/src/main/java/com/auth0/java/core/Strategy.java similarity index 89% rename from core/src/main/java/com/auth0/core/Strategy.java rename to core/src/main/java/com/auth0/java/core/Strategy.java index f06e007a..0d64ed0d 100644 --- a/core/src/main/java/com/auth0/core/Strategy.java +++ b/core/src/main/java/com/auth0/java/core/Strategy.java @@ -1,4 +1,4 @@ -package com.auth0.core; +package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -13,12 +13,12 @@ public class Strategy { private String name; - private List connections; + private List connections; private Strategies strategyMetadata; @JsonCreator public Strategy(@JsonProperty(value = "name", required = true) String name, - @JsonProperty(value = "connections", required = true) List connections) { + @JsonProperty(value = "connections", required = true) List connections) { this.name = name; this.connections = connections; this.strategyMetadata = Strategies.fromName(name); diff --git a/core/src/main/java/com/auth0/core/Token.java b/core/src/main/java/com/auth0/java/core/Token.java similarity index 50% rename from core/src/main/java/com/auth0/core/Token.java rename to core/src/main/java/com/auth0/java/core/Token.java index 0759233d..a862f255 100644 --- a/core/src/main/java/com/auth0/core/Token.java +++ b/core/src/main/java/com/auth0/java/core/Token.java @@ -1,7 +1,4 @@ -package com.auth0.core; - -import android.os.Parcel; -import android.os.Parcelable; +package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -10,7 +7,7 @@ * Class that holds a user's token information. */ @JsonIgnoreProperties(ignoreUnknown = true) -public class Token implements Parcelable { +public class Token { private String idToken; private String accessToken; @@ -42,37 +39,4 @@ public String getType() { public String getRefreshToken() { return refreshToken; } - - protected Token(Parcel in) { - idToken = in.readString(); - accessToken = in.readString(); - type = in.readString(); - refreshToken = in.readString(); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(idToken); - dest.writeString(accessToken); - dest.writeString(type); - dest.writeString(refreshToken); - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public com.auth0.core.Token createFromParcel(Parcel in) { - return new com.auth0.core.Token(in); - } - - @Override - public com.auth0.core.Token[] newArray(int size) { - return new com.auth0.core.Token[size]; - } - }; } diff --git a/core/src/main/java/com/auth0/core/UserIdentity.java b/core/src/main/java/com/auth0/java/core/UserIdentity.java similarity index 64% rename from core/src/main/java/com/auth0/core/UserIdentity.java rename to core/src/main/java/com/auth0/java/core/UserIdentity.java index 52dd8d2a..44d7840d 100644 --- a/core/src/main/java/com/auth0/core/UserIdentity.java +++ b/core/src/main/java/com/auth0/java/core/UserIdentity.java @@ -1,20 +1,16 @@ -package com.auth0.core; - -import android.os.Parcel; -import android.os.Parcelable; +package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.HashMap; import java.util.Map; /** * Class that holds the information from a Identity Provider like Facebook or Twitter. */ @JsonIgnoreProperties(ignoreUnknown = true) -public class UserIdentity implements Parcelable { +public class UserIdentity { private static final String USER_ID_KEY = "user_id"; private static final String CONNECTION_KEY = "connection"; @@ -93,52 +89,4 @@ public Map getProfileInfo() { public String getUserIdentityId() { return String.format("%s|%s", this.provider, this.id); } - - protected UserIdentity(Parcel in) { - id = in.readString(); - connection = in.readString(); - provider = in.readString(); - social = in.readByte() != 0x00; - accessToken = in.readString(); - accessTokenSecret = in.readString(); - if (in.readByte() == 0x01) { - profileInfo = (Map) in.readSerializable(); - } else { - profileInfo = new HashMap(); - } - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(id); - dest.writeString(connection); - dest.writeString(provider); - dest.writeByte((byte) (social ? 0x01 : 0x00)); - dest.writeString(accessToken); - dest.writeString(accessTokenSecret); - if (profileInfo == null) { - dest.writeByte((byte) 0x00); - } else { - dest.writeByte((byte) (0x01)); - dest.writeSerializable(new HashMap(profileInfo)); - } - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public com.auth0.core.UserIdentity createFromParcel(Parcel in) { - return new com.auth0.core.UserIdentity(in); - } - - @Override - public com.auth0.core.UserIdentity[] newArray(int size) { - return new com.auth0.core.UserIdentity[size]; - } - }; } diff --git a/core/src/main/java/com/auth0/core/UserProfile.java b/core/src/main/java/com/auth0/java/core/UserProfile.java similarity index 54% rename from core/src/main/java/com/auth0/core/UserProfile.java rename to core/src/main/java/com/auth0/java/core/UserProfile.java index 16b38580..95a5d181 100644 --- a/core/src/main/java/com/auth0/core/UserProfile.java +++ b/core/src/main/java/com/auth0/java/core/UserProfile.java @@ -1,8 +1,6 @@ -package com.auth0.core; - -import android.os.Parcel; -import android.os.Parcelable; +package com.auth0.java.core; +import com.auth0.java.util.CheckHelper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -16,13 +14,11 @@ import java.util.Map; import java.util.TimeZone; -import static com.auth0.util.CheckHelper.checkArgument; - /** * Class that holds the information of a user's profile */ @JsonIgnoreProperties(ignoreUnknown = true) -public class UserProfile implements Parcelable { +public class UserProfile { private String id; private String name; @@ -36,10 +32,10 @@ public class UserProfile implements Parcelable { @JsonCreator @SuppressWarnings("unchecked") public UserProfile(Map values) { - checkArgument(values != null, "must supply non-null values"); + CheckHelper.checkArgument(values != null, "must supply non-null values"); HashMap info = new HashMap(values); String id = (String) info.remove("user_id"); - checkArgument(id != null, "profile must have a user id"); + CheckHelper.checkArgument(id != null, "profile must have a user id"); this.id = id; this.name = (String) info.remove("name"); this.nickname = (String) info.remove("nickname"); @@ -107,66 +103,4 @@ private List buildIdentities(List> values) { } return identities; } - - @SuppressWarnings("unchecked") - protected UserProfile(Parcel in) { - id = in.readString(); - name = in.readString(); - nickname = in.readString(); - email = in.readString(); - pictureURL = in.readString(); - long tmpCreatedAt = in.readLong(); - createdAt = tmpCreatedAt != -1 ? new Date(tmpCreatedAt) : null; - if (in.readByte() == 0x01) { - identities = new ArrayList(); - in.readList(identities, UserIdentity.class.getClassLoader()); - } else { - identities = null; - } - if (in.readByte() == 0x01) { - extraInfo = (Map) in.readSerializable(); - } else { - extraInfo = new HashMap(); - } - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(id); - dest.writeString(name); - dest.writeString(nickname); - dest.writeString(email); - dest.writeString(pictureURL); - dest.writeLong(createdAt != null ? createdAt.getTime() : -1L); - if (identities == null) { - dest.writeByte((byte) (0x00)); - } else { - dest.writeByte((byte) (0x01)); - dest.writeList(identities); - } - if (extraInfo == null) { - dest.writeByte((byte) 0x00); - } else { - dest.writeByte((byte) (0x01)); - dest.writeSerializable(new HashMap(extraInfo)); - } - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public com.auth0.core.UserProfile createFromParcel(Parcel in) { - return new com.auth0.core.UserProfile(in); - } - - @Override - public com.auth0.core.UserProfile[] newArray(int size) { - return new com.auth0.core.UserProfile[size]; - } - }; } diff --git a/core/src/main/java/com/auth0/java/util/Build.java b/core/src/main/java/com/auth0/java/util/Build.java new file mode 100644 index 00000000..2d61cb2f --- /dev/null +++ b/core/src/main/java/com/auth0/java/util/Build.java @@ -0,0 +1,11 @@ +package com.auth0.java.util; + +public class Build { + public static String MANUFACTURER = "MANUFACTURER"; + public static String MODEL = "MODEL"; + public static Version VERSION = new Version(); + + public static class Version { + public static String RELEASE = "RELEASE"; + } +} diff --git a/core/src/main/java/com/auth0/util/CheckHelper.java b/core/src/main/java/com/auth0/java/util/CheckHelper.java similarity index 98% rename from core/src/main/java/com/auth0/util/CheckHelper.java rename to core/src/main/java/com/auth0/java/util/CheckHelper.java index c0871cb4..19ce912e 100644 --- a/core/src/main/java/com/auth0/util/CheckHelper.java +++ b/core/src/main/java/com/auth0/java/util/CheckHelper.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.util; +package com.auth0.java.util; /** * A helper to check constructor arguments. diff --git a/core/src/main/java/com/auth0/java/util/Log.java b/core/src/main/java/com/auth0/java/util/Log.java new file mode 100644 index 00000000..18054353 --- /dev/null +++ b/core/src/main/java/com/auth0/java/util/Log.java @@ -0,0 +1,23 @@ +package com.auth0.java.util; + +public class Log { + public static void d(String tag, String message) { + + } + + public static void e(String tag, String message) { + + } + + public static void e(String tag, String message, Throwable error) { + + } + + public static void v(String tag, String message) { + + } + + public static void w(String tag, String message) { + + } +} diff --git a/core/src/test/java/com/auth0/api/ParameterBuilderTest.java b/core/src/test/java/com/auth0/api/ParameterBuilderTest.java deleted file mode 100644 index 81998760..00000000 --- a/core/src/test/java/com/auth0/api/ParameterBuilderTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.auth0.api; - -import android.os.Build; - -import com.auth0.android.BuildConfig; -import com.auth0.api.ParameterBuilder; - -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class ParameterBuilderTest { - - public static final String CLIENT_ID = "CLIENT ID"; - public static final String GRANT_TYPE = "password"; - public static final String CONNECTION = "AD"; - public static final String DEVICE = "ANDROID TEST DEVICE"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private ParameterBuilder builder; - - @Before - public void setUp() throws Exception { - this.builder = ParameterBuilder.newBuilder(); - } - - @Test - public void shouldInstantiateWithNoArguments() throws Exception { - assertThat(new ParameterBuilder(), is(notNullValue())); - assertThat(ParameterBuilder.newBuilder(), is(notNullValue())); - } - - @Test - public void shouldInstantiateWithDefaultScope() throws Exception { - assertThat(new ParameterBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); - assertThat(ParameterBuilder.newBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); - } - - @Test - public void shouldInstantiateWithArguments() throws Exception { - assertThat(new ParameterBuilder(new HashMap()), is(notNullValue())); - assertThat(ParameterBuilder.newBuilder(new HashMap()), is(notNullValue())); - } - - @Test - public void shouldFailToInstantiateWithNullParameters() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); - new ParameterBuilder(null); - } - - @Test - public void shouldFailToInstantiateWithNullParametersInFactoryMethod() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); - ParameterBuilder.newBuilder(null); - } - - @Test - public void shouldSetClientID() throws Exception { - assertThat(builder.setClientId(CLIENT_ID).asDictionary(), hasEntry("client_id", CLIENT_ID)); - } - - @Test - public void shouldSetScope() throws Exception { - Map parameters = builder.setScope(ParameterBuilder.SCOPE_OPENID).asDictionary(); - assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); - assertThat(parameters, not(hasEntry("device", Build.MODEL))); - } - - @Test - public void shouldSetDevice() throws Exception { - Map parameters = builder.setDevice(DEVICE).asDictionary(); - assertThat(parameters, hasEntry("device", DEVICE)); - } - - @Test - public void shouldSetScopeWithOfflineAccess() throws Exception { - Map parameters = builder.setScope(ParameterBuilder.SCOPE_OFFLINE_ACCESS).asDictionary(); - assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); - assertThat(parameters, hasEntry("device", Build.MODEL)); - } - - @Test - public void shouldSetGrantType() throws Exception { - assertThat(builder.setGrantType(GRANT_TYPE).asDictionary(), hasEntry("grant_type", GRANT_TYPE)); - } - - @Test - public void shouldSetConnection() throws Exception { - assertThat(builder.setConnection(CONNECTION).asDictionary(), hasEntry("connection", CONNECTION)); - } - - @Test - public void shouldAddArbitraryEntry() throws Exception { - assertThat(builder.set("key", "value").asDictionary(), hasEntry("key", "value")); - } - - @Test - public void shouldAddAllFromDictionary() throws Exception { - Map parameters = new HashMap<>(); - parameters.put("key", "value"); - assertThat(builder.addAll(parameters).asDictionary(), hasEntry("key", "value")); - } - - @Test - public void shouldDoNothingWhenAddingNullParameters() throws Exception { - assertThat(builder.addAll(null).asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); - } - - @Test - public void shouldProvideADictionaryCopy() throws Exception { - Map parameters = builder.setClientId(CLIENT_ID).asDictionary(); - parameters.put("key", "value"); - assertThat(builder.asDictionary(), not(hasEntry("key", "value"))); - } - - private static Matcher> hasEntry(String key, Object value) { - return Matchers.hasEntry(key, value); - } -} diff --git a/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java deleted file mode 100644 index cbbd3003..00000000 --- a/core/src/test/java/com/auth0/api/authentication/AuthenticationAPIClientTest.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * AuthenticationAPIClientTest.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.api.authentication; - -import android.os.Handler; - -import com.auth0.android.BuildConfig; -import com.auth0.api.ParameterBuilder; -import com.auth0.api.authentication.AuthenticationAPIClient; -import com.auth0.core.Application; -import com.auth0.core.Auth0; -import com.auth0.core.DatabaseUser; -import com.auth0.core.Token; -import com.auth0.core.UserProfile; -import com.auth0.util.AuthenticationAPI; -import com.auth0.util.MockAuthenticationCallback; -import com.auth0.util.MockBaseCallback; -import com.auth0.util.MockRefreshIdTokenCallback; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.squareup.okhttp.mockwebserver.RecordedRequest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.util.HashMap; -import java.util.Map; - -import static com.auth0.util.AuthenticationAPI.GENERIC_TOKEN; -import static com.auth0.util.AuthenticationAPI.ID_TOKEN; -import static com.auth0.util.AuthenticationAPI.NEW_ID_TOKEN; -import static com.auth0.util.AuthenticationAPI.REFRESH_TOKEN; -import static com.auth0.util.AuthenticationCallbackMatcher.hasTokenAndProfile; -import static com.auth0.util.CallbackMatcher.hasNoError; -import static com.auth0.util.CallbackMatcher.hasNoPayloadOfType; -import static com.auth0.util.CallbackMatcher.hasPayload; -import static com.auth0.util.CallbackMatcher.hasPayloadOfType; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class AuthenticationAPIClientTest { - - private static final String CLIENT_ID = "CLIENTID"; - private static final String DOMAIN = "samples.auth0.com"; - private static final String CONNECTION = "DB"; - - private AuthenticationAPIClient client; - - private AuthenticationAPI mockAPI; - - @Before - public void setUp() throws Exception { - mockAPI = new AuthenticationAPI(); - final String domain = mockAPI.getDomain(); - Auth0 auth0 = new Auth0(CLIENT_ID, domain, domain); - Handler handler = mock(Handler.class); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Runnable runnable = (Runnable) invocation.getArguments()[0]; - runnable.run(); - return null; - } - }).when(handler).post(any(Runnable.class)); - client = new AuthenticationAPIClient(auth0, handler); - } - - @After - public void tearDown() throws Exception { - mockAPI.shutdown(); - } - - @Test - public void shouldCreateClientWithAccountInfo() throws Exception { - AuthenticationAPIClient client = new AuthenticationAPIClient(new Auth0(CLIENT_ID, DOMAIN)); - assertThat(client, is(notNullValue())); - assertThat(client.getClientId(), equalTo(CLIENT_ID)); - assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); - } - - @Test - public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { - mockAPI.willReturnValidApplicationResponse(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - - assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); - assertThat(callback, hasPayloadOfType(Application.class)); - } - - @Test - public void shoulFailWithInvalidJSON() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shoulFailWithInvalidJSONP() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shouldFailWithFailedStatusCode() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); - final MockBaseCallback callback = new MockBaseCallback<>(); - - client.fetchApplicationInfo() - .start(callback); - - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shouldLoginWithResourceOwner() throws Exception { - mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - final Map parameters = ParameterBuilder.newBuilder() - .setConnection("DB") - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") - .set("password", "notapassword") - .setScope(ParameterBuilder.SCOPE_OPENID) - .asDictionary(); - client.loginWithResourceOwner() - .addParameters(parameters) - .start(callback); - - assertThat(callback, hasPayloadOfType(Token.class)); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/ro")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "DB")); - assertThat(body, hasEntry("grant_type", "password")); - assertThat(body, hasEntry("username", "support@auth0.com")); - assertThat(body, hasEntry("password", "notapassword")); - assertThat(body, hasEntry("scope", "openid")); - } - - @Test - public void shouldFailLoginWithResourceOwner() throws Exception { - mockAPI.willReturnFailedLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - final Map parameters = ParameterBuilder.newBuilder() - .setConnection(CONNECTION) - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") - .set("password", "notapassword") - .asDictionary(); - client.loginWithResourceOwner() - .addParameters(parameters) - .start(callback); - - assertThat(callback, hasNoPayloadOfType(Token.class)); - } - - @Test - public void shouldLoginWithUserAndPassword() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - - client.login("support@auth0.com", "voidpassword") - .start(callback); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldFetchTokenInfo() throws Exception { - mockAPI.willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - client.tokenInfo("ID_TOKEN") - .start(callback); - - assertThat(callback, hasPayloadOfType(UserProfile.class)); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/tokeninfo")); - } - - @Test - public void shouldLoginWithOAuthAccessToken() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - client.loginWithOAuthAccessToken("fbtoken", "facebook") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/access_token")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "facebook")); - assertThat(body, hasEntry("access_token", "fbtoken")); - assertThat(body, hasEntry("scope", "openid offline_access")); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldLoginWithPhoneNumber() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - client.loginWithPhoneNumber("+10101010101", "1234") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/ro")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "sms")); - assertThat(body, hasEntry("username", "+10101010101")); - assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldLoginWithEmailOnly() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - client.loginWithEmail("support@auth0.com", "1234") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/ro")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "email")); - assertThat(body, hasEntry("username", "support@auth0.com")); - assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldCreateUser() throws Exception { - mockAPI.willReturnSuccessfulSignUp(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.createUser("support@auth0.com", "123123123", "support") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/dbconnections/signup")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); - - assertThat(callback, hasPayloadOfType(DatabaseUser.class)); - - } - - @Test - public void shouldCreateUserWithoutUsername() throws Exception { - mockAPI.willReturnSuccessfulSignUp(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.createUser("support@auth0.com", "123123123") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/dbconnections/signup")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); - assertThat(body, hasEntry("password", "123123123")); - - assertThat(callback, hasPayloadOfType(DatabaseUser.class)); - - } - - @Test - public void shouldSignUpUser() throws Exception { - mockAPI.willReturnSuccessfulSignUp() - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - client.signUp("support@auth0.com", "123123123", "support") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/dbconnections/signup")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldSignUpUserWithoutUsername() throws Exception { - mockAPI.willReturnSuccessfulSignUp() - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); - client.signUp("support@auth0.com", "123123123") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/dbconnections/signup")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); - assertThat(body, hasEntry("password", "123123123")); - - assertThat(callback, hasTokenAndProfile()); - } - - @Test - public void shouldChangePassword() throws Exception { - mockAPI.willReturnSuccessfulChangePassword(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.changePassword("support@auth0.com", "123123123") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/dbconnections/change_password")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); - assertThat(body, hasEntry("password", "123123123")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldCallDelegation() throws Exception { - mockAPI.willReturnGenericDelegationToken(); - - final MockBaseCallback> callback = new MockBaseCallback<>(); - client.delegation() - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/delegation")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - - Map payload = new HashMap<>(); - payload.put("token", GENERIC_TOKEN); - assertThat(callback, hasPayload(payload)); - } - - @Test - public void shouldGetNewIdTokenWithIdToken() throws Exception { - mockAPI.willReturnNewIdToken(); - - final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); - client.delegationWithIdToken(ID_TOKEN) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/delegation")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("api_type", "app")); - assertThat(body, hasEntry("id_token", ID_TOKEN)); - - assertThat(callback, hasPayload(NEW_ID_TOKEN)); - } - - @Test - public void shouldGetNewIdTokenWithRefreshToken() throws Exception { - mockAPI.willReturnNewIdToken(); - - final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); - client.delegationWithRefreshToken(REFRESH_TOKEN) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/delegation")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("api_type", "app")); - assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); - - assertThat(callback, hasPayload(NEW_ID_TOKEN)); - } - - @Test - public void shouldUnlinkAccount() throws Exception { - mockAPI.willReturnSuccessfulUnlinkAccount(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.unlink("user id", "access token") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/unlink")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("clientID", CLIENT_ID)); - assertThat(body, hasEntry("user_id", "user id")); - assertThat(body, hasEntry("access_token", "access token")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldStartPasswordless() throws Exception { - mockAPI.willReturnSuccessfulPasswordlessStart(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = new ParameterBuilder() - .clearAll() - .setConnection("email") - .set("send", "code") - .set("email", "support@auth0.com") - .asDictionary(); - client.passwordless() - .addParameters(parameters) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/passwordless/start")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("send", "code")); - assertThat(body, hasEntry("connection", "email")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldSendEmailCode() throws Exception { - mockAPI.willReturnSuccessfulPasswordlessStart(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", false) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/passwordless/start")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("send", "code")); - assertThat(body, hasEntry("connection", "email")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldSendEmailLink() throws Exception { - mockAPI.willReturnSuccessfulPasswordlessStart(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", true) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/passwordless/start")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("send", "link_android")); - assertThat(body, hasEntry("connection", "email")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldSendSMSCode() throws Exception { - mockAPI.willReturnSuccessfulPasswordlessStart(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithSMS("+1123123123", false) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/passwordless/start")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("phone_number", "+1123123123")); - assertThat(body, hasEntry("send", "code")); - assertThat(body, hasEntry("connection", "sms")); - - assertThat(callback, hasNoError()); - } - - @Test - public void shouldSendSMSLink() throws Exception { - mockAPI.willReturnSuccessfulPasswordlessStart(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithSMS("+1123123123", true) - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/passwordless/start")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("phone_number", "+1123123123")); - assertThat(body, hasEntry("send", "link_android")); - assertThat(body, hasEntry("connection", "sms")); - - assertThat(callback, hasNoError()); - } - - private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { - return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); - } -} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java deleted file mode 100644 index 116977f5..00000000 --- a/core/src/test/java/com/auth0/api/internal/BaseRequestTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * CallbackHandlerTest.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.api.internal; - -import android.os.Handler; - -import com.auth0.android.BuildConfig; -import com.auth0.api.ParameterizableRequest; -import com.auth0.api.callback.BaseCallback; -import com.auth0.api.internal.BaseRequest; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.squareup.okhttp.HttpUrl; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.io.IOException; -import java.util.Map; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class BaseRequestTest { - - private BaseRequest baseRequest; - - @Mock - private Handler handler; - @Mock - private BaseCallback callback; - @Mock - private Throwable throwable; - @Mock - private OkHttpClient client; - @Mock - private ObjectReader reader; - @Mock - private ObjectWriter writer; - @Captor - private ArgumentCaptor captor; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - HttpUrl url = HttpUrl.parse("https://auth0.com"); - baseRequest = new BaseRequest(handler, url, client, reader, writer, callback) { - @Override - protected Request doBuildRequest(Request.Builder builder) { - return null; - } - - @Override - public void onResponse(Response response) throws IOException { - - } - - @Override - public void start(BaseCallback callback) { - - } - - @Override - public ParameterizableRequest addParameters(Map parameters) { - return null; - } - }; - } - - @Test - public void shouldPostOnSuccess() throws Exception { - baseRequest.postOnSuccess("OK"); - verify(handler).post(captor.capture()); - Runnable runnable = captor.getValue(); - runnable.run(); - verify(callback).onSuccess(eq("OK")); - verifyNoMoreInteractions(callback, handler); - } - - @Test - public void shouldPostOnFailure() throws Exception { - baseRequest.postOnFailure(throwable); - verify(handler).post(captor.capture()); - Runnable runnable = captor.getValue(); - runnable.run(); - verify(callback).onFailure(eq(throwable)); - verifyNoMoreInteractions(callback, handler); - } -} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/core/ApplicationTest.java b/core/src/test/java/com/auth0/core/ApplicationTest.java deleted file mode 100644 index 9789c5ad..00000000 --- a/core/src/test/java/com/auth0/core/ApplicationTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.auth0.core; - -import com.auth0.android.BuildConfig; -import com.auth0.core.Application; -import com.auth0.core.Connection; -import com.auth0.core.Strategies; -import com.auth0.core.Strategy; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.util.Arrays; -import java.util.List; - -import static com.auth0.core.Strategies.ADFS; -import static com.auth0.core.Strategies.Auth0; -import static com.auth0.core.Strategies.Facebook; -import static com.auth0.core.Strategies.Office365; -import static com.auth0.core.Strategies.SAMLP; -import static com.auth0.core.Strategies.Twitter; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.mock; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class ApplicationTest { - - public static final String ID = "ID"; - public static final String TENANT = "TENANT"; - public static final String AUTHORIZE_URL = "AUTHORIZE"; - public static final String CALLBACK_URL = "CALLBACK"; - public static final String SUBSCRIPTION = "SUBSCRIPTION"; - public static final boolean HAS_ALLOWED_ORIGINS = true; - - @Test - public void shouldInstantiateApplication() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application, is(notNullValue())); - } - - @Test - public void shouldHaveApplicationInfo() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application.getId(), equalTo(ID)); - assertThat(application.getTenant(), equalTo(TENANT)); - assertThat(application.getAuthorizeURL(), equalTo(AUTHORIZE_URL)); - assertThat(application.getCallbackURL(), equalTo(CALLBACK_URL)); - assertThat(application.getSubscription(), equalTo(SUBSCRIPTION)); - assertThat(application.isHasAllowedOrigins(), equalTo(HAS_ALLOWED_ORIGINS)); - } - - @Test - public void shouldReturnDatabaseStrategy() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application.getDatabaseStrategy(), is(notNullValue())); - assertThat(application.getDatabaseStrategy().getName(), equalTo(Auth0.getName())); - } - - @Test - public void shouldReturnNoDatabaseStrategy() throws Exception { - Application application = newApplicationWithStrategies(Facebook); - assertThat(application.getDatabaseStrategy(), is(nullValue())); - } - - @Test - public void shouldReturnSocialStrategies() throws Exception { - Application application = newApplicationWithStrategies(Facebook, Twitter, Auth0); - assertThat(application.getSocialStrategies().size(), equalTo(2)); - } - - @Test - public void shouldReturnEnterpriseStrategies() throws Exception { - Application application = newApplicationWithStrategies(Auth0, ADFS, SAMLP, Office365); - assertThat(application.getEnterpriseStrategies().size(), equalTo(3)); - } - - private static Strategy newStrategyFor(Strategies strategyMetadata) { - return new Strategy(strategyMetadata.getName(), Arrays.asList(mock(Connection.class))); - } - - private static Application newApplicationWithStrategies(Strategies... list) { - List strategies = Lists.newArrayList(); - for (Strategies str: list) { - strategies.add(newStrategyFor(str)); - } - Application application = new Application(ID, TENANT, AUTHORIZE_URL, CALLBACK_URL, SUBSCRIPTION, HAS_ALLOWED_ORIGINS, strategies); - return application; - } -} diff --git a/core/src/test/java/com/auth0/core/Auth0Test.java b/core/src/test/java/com/auth0/core/Auth0Test.java deleted file mode 100644 index 540ae1c0..00000000 --- a/core/src/test/java/com/auth0/core/Auth0Test.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Auth0Test.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.core; - -import com.auth0.android.BuildConfig; -import com.auth0.api.APIClient; -import com.auth0.core.Auth0; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class Auth0Test { - - private static final String CLIENT_ID = "CLIENT_ID"; - private static final String DOMAIN = "samples.auth0.com"; - private static final String CONFIG_DOMAIN_CUSTOM = "config.mydomain.com"; - private static final String EU_DOMAIN = "samples.eu.auth0.com"; - private static final String AU_DOMAIN = "samples.au.auth0.com"; - private static final String OTHER_DOMAIN = "samples-test.other-subdomain.other.auth0.com"; - - @Test - public void shouldBuildWithClientIdAndDomain() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.auth0.com")); - } - - @Test - public void shouldBuildWithConfigurationDomainToo() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN, CONFIG_DOMAIN_CUSTOM); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://config.mydomain.com")); - } - - @Test - public void shouldHandleEUInstance() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, EU_DOMAIN); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://samples.eu.auth0.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.eu.auth0.com")); - } - - @Test - public void shouldHandleAUInstance() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, AU_DOMAIN); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://samples.au.auth0.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.au.auth0.com")); - } - - @Test - public void shouldHandleOtherInstance() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, OTHER_DOMAIN); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://samples-test.other-subdomain.other.auth0.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.other.auth0.com")); - } - - @Test - public void shouldHandleNonAuth0Domain() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, "mydomain.com"); - assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); - assertThat(auth0.getDomainUrl(), equalTo("https://mydomain.com")); - assertThat(auth0.getConfigurationUrl(), equalTo("https://mydomain.com")); - } - - @Test - public void shouldBuildNewClient() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); - APIClient client = auth0.newAPIClient(); - assertThat(client, is(notNullValue())); - assertThat(client.getConfigurationURL(), startsWith("https://cdn.auth0.com/")); - assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); - assertThat(client.getClientID(), equalTo(CLIENT_ID)); - } - - @Test - public void shouldReturnAuthorizeUrl() throws Exception { - Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); - assertThat(auth0.getAuthorizeUrl(), equalTo("https://samples.auth0.com/authorize")); - } -} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/core/ConnectionTest.java b/core/src/test/java/com/auth0/core/ConnectionTest.java deleted file mode 100644 index 582fe943..00000000 --- a/core/src/test/java/com/auth0/core/ConnectionTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.auth0.core; - -import com.auth0.android.BuildConfig; -import com.auth0.core.Connection; -import com.google.common.collect.Maps; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.util.Arrays; -import java.util.Map; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class ConnectionTest { - - public static final String CONNECTION_NAME = "Username-Password"; - public static final Object VALUE = "value"; - public static final String KEY = "key"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void shouldBuildConnectionWithName() { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertNotNull(connection); - assertThat(connection.getName(), equalTo(CONNECTION_NAME)); - } - - @Test - public void shouldBuildConnectionWithValues() { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - assertThat(connection.getValues(), hasEntry(KEY, VALUE)); - } - - @Test - public void shouldNotStoreNameInValues() throws Exception { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertThat(connection.getValues(), not(hasKey("name"))); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldRaiseExceptionWhenNameIsNull() { - Map values = null; - new Connection(values); - } - - @Test - public void shouldReturnValueFromKey() { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - String value = connection.getValueForKey(KEY); - assertThat(value, equalTo(VALUE)); - } - - @Test - public void shouldReturnBooleanValueFromKey() { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put(KEY, true); - Connection connection = new Connection(values); - boolean value = connection.booleanForKey(KEY); - assertThat(value, is(true)); - } - - @Test - public void shouldReturnDefaultBooleanValueFromKey() { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - boolean value = connection.booleanForKey(KEY); - assertThat(value, is(false)); - } - - @Test - public void shouldRaiseExceptionWhenValueIsNotBoolean() { - expectedException.expect(ClassCastException.class); - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - connection.booleanForKey(KEY); - } - - @Test - public void shouldReturnDomainNameInSet() throws Exception { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put("domain", "domain.com"); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet(), hasItem("domain.com")); - } - - @Test - public void shouldReturnAllDomainNamesAsSet() throws Exception { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - values.put("domain", "domain.com"); - values.put("domain_aliases", Arrays.asList("domain2.com", "domain3.com")); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet(), hasItems("domain.com", "domain2.com", "domain3.com")); - } - - @Test - public void shouldReturnEmptySetWithNoDomainName() throws Exception { - Map values = Maps.newHashMap(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet().isEmpty(), is(true)); - } -} diff --git a/core/src/test/java/com/auth0/core/StrategiesTest.java b/core/src/test/java/com/auth0/core/StrategiesTest.java deleted file mode 100644 index aaaa83a9..00000000 --- a/core/src/test/java/com/auth0/core/StrategiesTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.auth0.core; - -import com.auth0.android.BuildConfig; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import static org.junit.Assert.assertEquals; - - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class StrategiesTest { - @Test - public void shouldReturnUnknownSocial() { - Strategies unknownSocial = Strategies.fromName("this-strategy-does-not-exist"); - assertEquals(unknownSocial.getType(), Strategies.Type.SOCIAL); - } - - @Test - public void shouldReturnValidDatabaseStrategy() { - Strategies auth0Database = Strategies.fromName("auth0"); - assertEquals(auth0Database.getType(), Strategies.Type.DATABASE); - } -} diff --git a/core/src/test/java/com/auth0/core/UserProfileTest.java b/core/src/test/java/com/auth0/core/UserProfileTest.java deleted file mode 100644 index 84e20e43..00000000 --- a/core/src/test/java/com/auth0/core/UserProfileTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.auth0.core; - -import com.auth0.android.BuildConfig; -import com.auth0.core.UserIdentity; -import com.auth0.core.UserProfile; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.annotation.Config; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18, manifest = Config.NONE) -public class UserProfileTest { - - public static final String USER_ID = "IOU a user id"; - public static final String NAME = "Somebody Someone"; - public static final String NICKNAME = "somebody"; - public static final String EMAIL = "somebody@somwhere.com"; - public static final String CREATED_AT = "2014-07-06T18:33:49.005Z"; - public static final String PICTURE_URL = "http://somewhere.com/pic.jpg"; - public static final Object EXTRA_VALUE = "extra_value"; - public static final long CREATED_AT_TIMESTAMP = 1404671629005l; - public static final String FACEBOOK = "facebook"; - public static final String TOKEN = "token"; - public static final String SECRET = "secret"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void shouldRaiseExceptionWithNullValuesWhenCreatingInstance() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(equalTo("must supply non-null values")); - new UserProfile((HashMap)null); - } - - @Test - public void shouldRaiseExceptionWithNoUserIdWhenCreatingInstance() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(equalTo("profile must have a user id")); - new UserProfile(new HashMap()); - } - - @Test - public void shouldInstantiateProfileWithId() throws Exception { - Map values = new HashMap(); - values.put("user_id", USER_ID); - UserProfile profile = new UserProfile(values); - assertValidProfile(profile); - } - - @Test - public void shouldInstantiateWithBasicProfileInfo() throws Exception { - Map values = new HashMap(); - values.put("user_id", USER_ID); - values.put("name", NAME); - values.put("nickname", NICKNAME); - values.put("email", EMAIL); - values.put("picture", PICTURE_URL); - values.put("created_at", CREATED_AT); - UserProfile profile = new UserProfile(values); - assertValidProfile(profile); - assertThat(profile.getName(), equalTo(NAME)); - assertThat(profile.getNickname(), equalTo(NICKNAME)); - assertThat(profile.getEmail(), equalTo(EMAIL)); - assertThat(profile.getPictureURL(), equalTo(PICTURE_URL)); - assertThat(profile.getCreatedAt().getTime(), equalTo(CREATED_AT_TIMESTAMP)); - assertThat(profile.getExtraInfo().size(), equalTo(0)); - } - - @Test - public void shouldHandleExtraProfileInfo() throws Exception { - Map values = new HashMap(); - values.put("user_id", USER_ID); - values.put("extra_key", EXTRA_VALUE); - UserProfile profile = new UserProfile(values); - assertValidProfile(profile); - assertThat(profile.getExtraInfo(), hasEntry("extra_key", EXTRA_VALUE)); - } - - @Test - public void shouldHandleIdentities() throws Exception { - Map values = new HashMap(); - Map identityValue = new HashMap<>(); - Map profileData = new HashMap<>(); - identityValue.put("user_id", USER_ID); - identityValue.put("connection", FACEBOOK); - identityValue.put("provider", FACEBOOK); - identityValue.put("isSocial", true); - identityValue.put("access_token", TOKEN); - identityValue.put("access_token_secret", SECRET); - identityValue.put("profileData", profileData); - profileData.put("name", "John Doe"); - - values.put("user_id", USER_ID); - values.put("identities", Collections.singletonList(identityValue)); - UserProfile profile = new UserProfile(values); - assertValidProfile(profile); - assertThat(profile.getIdentities(), hasSize(1)); - UserIdentity identity = profile.getIdentities().get(0); - assertThat(identity, isA(UserIdentity.class)); - assertThat(identity.getId(), equalTo(USER_ID)); - assertThat(identity.getProvider(), equalTo(FACEBOOK)); - assertThat(identity.getConnection(), equalTo(FACEBOOK)); - assertThat(identity.getAccessToken(), equalTo(TOKEN)); - assertThat(identity.getAccessTokenSecret(), equalTo(SECRET)); - } - - private void assertValidProfile(UserProfile profile) { - assertThat(profile, is(notNullValue())); - assertThat(profile.getId(), equalTo(USER_ID)); - } -} diff --git a/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java b/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java deleted file mode 100644 index ff859426..00000000 --- a/core/src/test/java/com/auth0/util/APIClientExceptionMatcher.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * APIExceptionMather.java - * - * Copyright (c) 2014 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.auth0.api.APIClientException; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; - -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; - -public class APIClientExceptionMatcher extends BaseMatcher { - - private Matcher causeMatcher; - private Matcher statusCodeMatcher; - private Matcher> errorMatcher; - - private APIClientExceptionMatcher() {} - - private APIClientExceptionMatcher(Matcher causeMatcher, Matcher statusCodeMatcher, Matcher> errorMatcher) { - this.causeMatcher = causeMatcher; - this.statusCodeMatcher = statusCodeMatcher; - this.errorMatcher = errorMatcher; - } - - @Override - public boolean matches(Object o) { - APIClientException exception = (APIClientException) o; - return causeMatcher.matches(exception.getCause()) - && statusCodeMatcher.matches(exception.getStatusCode()) - && errorMatcher.matches(exception.getResponseError()); - } - - @Override - public void describeTo(Description description) { - description - .appendText("APIClientException with values: ") - .appendDescriptionOf(causeMatcher) - .appendText(" ") - .appendDescriptionOf(statusCodeMatcher) - .appendText(" ") - .appendDescriptionOf(errorMatcher) - .appendText(" "); - } - - public static Matcher hasGenericErrorWith(int statusCode, Throwable cause) { - return new APIClientExceptionMatcher(equalTo(cause), equalTo(statusCode), Matchers.>equalTo(new HashMap())); - } - - public static Matcher hasErrorWith(int statusCode, Throwable cause, Object error) { - return new APIClientExceptionMatcher(equalTo(cause), equalTo(statusCode), hasEntry("error", error)); - } -} diff --git a/core/src/test/java/com/auth0/util/AuthenticationAPI.java b/core/src/test/java/com/auth0/util/AuthenticationAPI.java deleted file mode 100644 index 437ab1f7..00000000 --- a/core/src/test/java/com/auth0/util/AuthenticationAPI.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * AuthenticationAPI.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.squareup.okhttp.mockwebserver.MockResponse; -import com.squareup.okhttp.mockwebserver.MockWebServer; -import com.squareup.okhttp.mockwebserver.RecordedRequest; - -import java.io.IOException; - -public class AuthenticationAPI { - - public static final String REFRESH_TOKEN = "REFRESH_TOKEN"; - public static final String ID_TOKEN = "ID_TOKEN"; - public static final String ACCESS_TOKEN = "ACCESS_TOKEN"; - public static final String BEARER = "BEARER"; - public static final String GENERIC_TOKEN = "GENERIC_TOKEN"; - public static final String NEW_ID_TOKEN = "NEW_ID_TOKEN"; - public static final int EXPIRES_IN = 1234567890; - public static final String TOKEN_TYPE = "TOKEN_TYPE"; - - private MockWebServer server; - - public AuthenticationAPI() throws IOException { - this.server = new MockWebServer(); - this.server.start(); - } - - public String getDomain() { - return server.url("/").toString(); - } - - public void shutdown() throws IOException { - this.server.shutdown(); - } - - public RecordedRequest takeRequest() throws InterruptedException { - return server.takeRequest(); - } - - public AuthenticationAPI willReturnValidApplicationResponse() { - return willReturnApplicationResponseWithBody("Auth0.setClient({\"id\":\"CLIENTID\",\"tenant\":\"overmind\",\"subscription\":\"free\",\"authorize\":\"https://samples.auth0.com/authorize\",\"callback\":\"http://localhost:3000/\",\"hasAllowedOrigins\":true,\"strategies\":[{\"name\":\"twitter\",\"connections\":[{\"name\":\"twitter\"}]}]});", 200); - } - - public AuthenticationAPI willReturnSuccessfulChangePassword() { - server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); - return this; - } - - public AuthenticationAPI willReturnSuccessfulUnlinkAccount() { - server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); - return this; - } - - public AuthenticationAPI willReturnGenericDelegationToken() { - String json = "{\n" + - " \"token\": \"" + GENERIC_TOKEN + "\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnSuccessfulPasswordlessStart() { - String json = "{\n" + - " \"phone+number\": \"+1098098098\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnNewIdToken() { - String json = "{\n" + - " \"id_token\": \"" + NEW_ID_TOKEN + "\",\n" + - " \"expires_in\": " + EXPIRES_IN + ",\n" + - " \"token_type\": \"" + TOKEN_TYPE + "\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnSuccessfulSignUp() { - String json = "{\n" + - " \"_id\": \"gjsmgdkjs72jljsf2dsdhh\", \n" + - " \"email\": \"support@auth0.com\", \n" + - " \"email_verified\": false, \n" + - " \"username\": \"support\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnSuccessfulLogin() { - String json = "{\n" + - " \"refresh_token\": \"" + REFRESH_TOKEN + "\",\n" + - " \"id_token\": \"" + ID_TOKEN + "\",\n" + - " \"access_token\": \"" + ACCESS_TOKEN + "\",\n" + - " \"token_type\": \"" + BEARER + "\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnFailedLogin() { - String json = "{\n" + - " \"error\": \"invalid_request\",\n" + - " \"error_description\": \"a random error\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 400)); - return this; - } - - public AuthenticationAPI willReturnTokenInfo() { - String json = "{\n" + - " \"email\": \"p@p.xom\",\n" + - " \"email_verified\": false,\n" + - " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + - " \"user_id\": \"auth0|53b995f8bce68d9fc900099c\",\n" + - " \"name\": \"p@p.xom\",\n" + - " \"nickname\": \"p\",\n" + - " \"identities\": [\n" + - " {\n" + - " \"user_id\": \"53b995f8bce68d9fc900099c\",\n" + - " \"provider\": \"auth0\",\n" + - " \"connection\": \"Username-Password-Authentication\",\n" + - " \"isSocial\": false\n" + - " }\n" + - " ],\n" + - " \"created_at\": \"2014-07-06T18:33:49.005Z\",\n" + - " \"username\": \"p\",\n" + - " \"updated_at\": \"2015-09-30T19:43:48.499Z\"\n" + - "}"; - server.enqueue(responseWithJSON(json, 200)); - return this; - } - - public AuthenticationAPI willReturnApplicationResponseWithBody(String body, int statusCode) { - MockResponse response = new MockResponse() - .setResponseCode(statusCode) - .addHeader("Content-Type", "application/x-javascript") - .setBody(body); - server.enqueue(response); - return this; - } - - private MockResponse responseWithJSON(String json, int statusCode) { - return new MockResponse() - .setResponseCode(statusCode) - .addHeader("Content-Type", "application/json") - .setBody(json); - } - -} diff --git a/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java b/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java deleted file mode 100644 index 54600eb0..00000000 --- a/core/src/test/java/com/auth0/util/AuthenticationCallbackMatcher.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * AuthenticationCallbackMatcher.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.auth0.core.Token; -import com.auth0.core.UserProfile; -import com.jayway.awaitility.core.ConditionTimeoutException; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import static com.jayway.awaitility.Awaitility.await; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; - -public class AuthenticationCallbackMatcher extends BaseMatcher { - - private final Matcher tokenMatcher; - private final Matcher profileMatcher; - private final Matcher errorMatcher; - - public AuthenticationCallbackMatcher(Matcher tokenMatcher, Matcher profileMatcher, Matcher errorMatcher) { - this.tokenMatcher = tokenMatcher; - this.profileMatcher = profileMatcher; - this.errorMatcher = errorMatcher; - } - - @Override - public boolean matches(Object item) { - MockAuthenticationCallback callback = (MockAuthenticationCallback) item; - try { - await().until(callback.token(), tokenMatcher); - await().until(callback.profile(), profileMatcher); - await().until(callback.error(), errorMatcher); - return true; - } catch (ConditionTimeoutException e) { - return false; - } - } - - @Override - public void describeTo(Description description) { - description - .appendText("successful method be called"); - } - - public static Matcher hasTokenAndProfile() { - return new AuthenticationCallbackMatcher(is(notNullValue(Token.class)), is(notNullValue(UserProfile.class)), is(nullValue(Throwable.class))); - } - - public static Matcher hasNeitherTokeNorProfile() { - return new AuthenticationCallbackMatcher(is(nullValue(Token.class)), is(nullValue(UserProfile.class)), is(notNullValue(Throwable.class))); - } - -} diff --git a/core/src/test/java/com/auth0/util/CallbackMatcher.java b/core/src/test/java/com/auth0/util/CallbackMatcher.java deleted file mode 100644 index 59e2fb4a..00000000 --- a/core/src/test/java/com/auth0/util/CallbackMatcher.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * CallbackMatcher.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.jayway.awaitility.core.ConditionTimeoutException; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import static com.jayway.awaitility.Awaitility.await; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; - -public class CallbackMatcher extends BaseMatcher> { - private final Matcher payloadMatcher; - private final Matcher errorMatcher; - - public CallbackMatcher( Matcher payloadMatcher, Matcher errorMatcher) { - this.payloadMatcher = payloadMatcher; - this.errorMatcher = errorMatcher; - } - - @Override - @SuppressWarnings("unchecked") - public boolean matches(Object item) { - MockBaseCallback callback = (MockBaseCallback) item; - try { - await().until(callback.payload(), payloadMatcher); - await().until(callback.error(), errorMatcher); - return true; - } catch (ConditionTimeoutException e) { - return false; - } - } - - @Override - public void describeTo(Description description) { - description - .appendText("successful method be called"); - } - - public static Matcher> hasPayloadOfType(Class clazz) { - return new CallbackMatcher<>(isA(clazz), is(nullValue(Throwable.class))); - } - - public static Matcher> hasPayload(T payload) { - return new CallbackMatcher<>(equalTo(payload), is(nullValue(Throwable.class))); - } - - public static Matcher> hasNoPayloadOfType(Class clazz) { - return new CallbackMatcher<>(is(nullValue(clazz)), is(notNullValue(Throwable.class))); - } - - public static Matcher> hasNoError() { - return new CallbackMatcher<>(is(nullValue(Void.class)), is(nullValue(Throwable.class))); - } - - public static Matcher> hasError() { - return new CallbackMatcher<>(is(nullValue(Void.class)), is(notNullValue(Throwable.class))); - } -} diff --git a/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java b/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java deleted file mode 100644 index b3574d6b..00000000 --- a/core/src/test/java/com/auth0/util/MockAuthenticationCallback.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * MockAuthenticationCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.auth0.api.callback.AuthenticationCallback; -import com.auth0.core.Token; -import com.auth0.core.UserProfile; - -import java.util.concurrent.Callable; - -public class MockAuthenticationCallback implements AuthenticationCallback { - - private Token token; - private UserProfile profile; - private Throwable error; - - @Override - public void onSuccess(UserProfile profile, Token token) { - this.token = token; - this.profile = profile; - } - - @Override - public void onFailure(Throwable error) { - this.error = error; - } - - public Callable token() { - return new Callable() { - @Override - public Token call() throws Exception { - return token; - } - }; - } - - public Callable profile() { - return new Callable() { - @Override - public UserProfile call() throws Exception { - return profile; - } - }; - } - - public Callable error() { - return new Callable() { - @Override - public Throwable call() throws Exception { - return error; - } - }; - } -} diff --git a/core/src/test/java/com/auth0/util/MockBaseCallback.java b/core/src/test/java/com/auth0/util/MockBaseCallback.java deleted file mode 100644 index fe34b526..00000000 --- a/core/src/test/java/com/auth0/util/MockBaseCallback.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * MockBaseCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.auth0.api.callback.BaseCallback; - -import java.util.concurrent.Callable; - -public class MockBaseCallback implements BaseCallback { - - private T payload; - private Throwable error; - - @Override - public void onSuccess(T payload) { - this.payload = payload; - } - - @Override - public void onFailure(Throwable error) { - this.error = error; - } - - public Callable payload() { - return new Callable() { - @Override - public T call() throws Exception { - return payload; - } - }; - } - - public Callable error() { - return new Callable() { - @Override - public Throwable call() throws Exception { - return error; - } - }; - } -} diff --git a/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java b/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java deleted file mode 100644 index 37bd52b6..00000000 --- a/core/src/test/java/com/auth0/util/MockRefreshIdTokenCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * MockRefreshIdTokenCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.util; - -import com.auth0.api.callback.RefreshIdTokenCallback; - -public class MockRefreshIdTokenCallback extends MockBaseCallback implements RefreshIdTokenCallback { - - @Override - public void onSuccess(String idToken, String tokenType, int expiresIn) { - onSuccess(idToken); - } - -} From 750b90cfd0d381cac2096208c3c444af9e9de226 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 11 Jan 2016 15:30:33 -0300 Subject: [PATCH 05/89] declare protected vars and add copy/default constructors --- .../java/com/auth0/java/core/Connection.java | 12 +++++-- .../main/java/com/auth0/java/core/Token.java | 19 +++++++++--- .../com/auth0/java/core/UserIdentity.java | 18 ++++++----- .../java/com/auth0/java/core/UserProfile.java | 31 ++++++++++++++----- 4 files changed, 59 insertions(+), 21 deletions(-) diff --git a/core/src/main/java/com/auth0/java/core/Connection.java b/core/src/main/java/com/auth0/java/core/Connection.java index 14741109..799b593a 100644 --- a/core/src/main/java/com/auth0/java/core/Connection.java +++ b/core/src/main/java/com/auth0/java/core/Connection.java @@ -15,9 +15,17 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class Connection { - private String name; + protected String name; + protected Map values; - private Map values; + protected Connection(Connection connection) { + name = connection.name; + values = connection.values; + } + + protected Connection() { + + } /** * Creates a new connection instance diff --git a/core/src/main/java/com/auth0/java/core/Token.java b/core/src/main/java/com/auth0/java/core/Token.java index a862f255..79868369 100644 --- a/core/src/main/java/com/auth0/java/core/Token.java +++ b/core/src/main/java/com/auth0/java/core/Token.java @@ -9,10 +9,21 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class Token { - private String idToken; - private String accessToken; - private String type; - private String refreshToken; + protected String idToken; + protected String accessToken; + protected String type; + protected String refreshToken; + + protected Token(Token token) { + idToken = token.idToken; + accessToken = token.accessToken; + type = token.type; + refreshToken = token.refreshToken; + } + + protected Token() { + + } public Token(@JsonProperty(value = "id_token", required = true) String idToken, @JsonProperty(value = "access_token") String accessToken, diff --git a/core/src/main/java/com/auth0/java/core/UserIdentity.java b/core/src/main/java/com/auth0/java/core/UserIdentity.java index 44d7840d..1ae2c994 100644 --- a/core/src/main/java/com/auth0/java/core/UserIdentity.java +++ b/core/src/main/java/com/auth0/java/core/UserIdentity.java @@ -19,13 +19,17 @@ public class UserIdentity { private static final String ACCESS_TOKEN_KEY = "access_token"; private static final String ACCESS_TOKEN_SECRET_KEY = "access_token_secret"; private static final String PROFILE_DATA_KEY = "profileData"; - private String id; - private String connection; - private String provider; - private boolean social; - private String accessToken; - private String accessTokenSecret; - private Map profileInfo; + protected String id; + protected String connection; + protected String provider; + protected boolean social; + protected String accessToken; + protected String accessTokenSecret; + protected Map profileInfo; + + protected UserIdentity() { + + } @SuppressWarnings("unchecked") public UserIdentity(Map values) { diff --git a/core/src/main/java/com/auth0/java/core/UserProfile.java b/core/src/main/java/com/auth0/java/core/UserProfile.java index 95a5d181..957b4f99 100644 --- a/core/src/main/java/com/auth0/java/core/UserProfile.java +++ b/core/src/main/java/com/auth0/java/core/UserProfile.java @@ -20,14 +20,29 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class UserProfile { - private String id; - private String name; - private String nickname; - private String email; - private String pictureURL; - private Date createdAt; - private Map extraInfo; - private List identities; + protected String id; + protected String name; + protected String nickname; + protected String email; + protected String pictureURL; + protected Date createdAt; + protected Map extraInfo; + protected List identities; + + protected UserProfile(UserProfile userProfile) { + id = userProfile.id; + name = userProfile.name; + nickname = userProfile.nickname; + email = userProfile.email; + pictureURL = userProfile.pictureURL; + createdAt = userProfile.createdAt; + extraInfo = userProfile.extraInfo; + identities = userProfile.identities; + } + + protected UserProfile() { + + } @JsonCreator @SuppressWarnings("unchecked") From 130d1c88ee7c1bf9bc89f5948337e6964ad1d285 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 11 Jan 2016 15:31:36 -0300 Subject: [PATCH 06/89] Add protected to enable the use from the subclass --- .../auth0/java/api/authentication/AuthenticationAPIClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java index c1303588..3921b766 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java @@ -85,7 +85,7 @@ public AuthenticationAPIClient(String clientID, String baseURL, String configura this(new Auth0(clientID, baseURL, configurationURL)); } - AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { + protected AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { this.auth0 = auth0; this.client = client; this.mapper = mapper; From 418ae2bf9ab97071b95a414f9306312117d5c48e Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 11 Jan 2016 15:56:19 -0300 Subject: [PATCH 07/89] Fix error when string is too short --- .../com/auth0/java/api/internal/ApplicationInfoRequest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java index a47c1aa0..5194bb2e 100644 --- a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java @@ -71,6 +71,9 @@ public void onResponse(Response response) throws IOException { } try { String json = response.body().string(); + if (json.length() < 16) { + throw new JSONException("Failed to parse JSONP"); + } json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method JSONTokener tokenizer = new JSONTokener(json); //tokenizer.skipPast("Auth0.setClient("); From b7f516e94a62330659d4722fb1274322a2e4754f Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 11 Jan 2016 15:57:58 -0300 Subject: [PATCH 08/89] [WIP] sync mode --- .../main/java/com/auth0/java/api/Request.java | 1 + .../auth0/java/api/internal/BaseRequest.java | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/core/src/main/java/com/auth0/java/api/Request.java b/core/src/main/java/com/auth0/java/api/Request.java index 5f91b376..b54e9bbc 100644 --- a/core/src/main/java/com/auth0/java/api/Request.java +++ b/core/src/main/java/com/auth0/java/api/Request.java @@ -33,5 +33,6 @@ public interface Request { void start(BaseCallback callback); + T execute() throws Throwable; } diff --git a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java index bec2b6d2..53e0ffa1 100644 --- a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java @@ -31,6 +31,8 @@ import com.auth0.java.api.callback.BaseCallback; import com.auth0.java.util.Build; import com.auth0.java.util.Log; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; @@ -38,8 +40,10 @@ import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; import java.io.IOException; +import java.io.InputStream; import java.util.HashMap; import java.util.Map; @@ -53,6 +57,7 @@ abstract class BaseRequest implements ParameterizableRequest, Authorizable private final OkHttpClient client; private final ObjectReader reader; private final ObjectWriter writer; + protected final ObjectReader errorReader; private BaseCallback callback; @@ -69,6 +74,8 @@ public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, Object this.headers = new HashMap<>(); this.parameters = new HashMap<>(); this.headers.put("User-Agent", String.format("Android %s (%s %s;)", Build.VERSION.RELEASE, Build.MODEL, Build.MANUFACTURER)); + // TODO fix this, pass object mapper as parameter + this.errorReader = new ObjectMapper().reader(new TypeReference>() {}); } protected void setCallback(BaseCallback callback) { @@ -150,5 +157,45 @@ public void start(BaseCallback callback) { } } + @Override + public T execute() throws Throwable { + Request request; + try { + request = doBuildRequest(newBuilder()); + } catch (RequestBodyBuildException e) { + Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); + throw new APIClientException("Failed to send request to " + url.toString(), e); + } + + Response response; + try { + response = client.newCall(request).execute(); + } catch (IOException e) { + Log.e(TAG, "Request failed to execute", e); + throw new APIClientException("Failed to execute request to " + url.toString(), e); + } + + Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); + final InputStream byteStream = response.body().byteStream(); + if (!response.isSuccessful()) { + Throwable throwable; + try { + Map payload = errorReader.readValue(byteStream); + throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); + } catch (IOException e) { + throwable = new APIClientException("Request failed", response.code(), null); + } + throw throwable; + } + + try { + Log.d(TAG, "Received successful response from " + response.request().urlString()); + T payload = getReader().readValue(byteStream); + return payload; + } catch (IOException e) { + throw new APIClientException("Request failed", response.code(), null); + } + } + protected abstract Request doBuildRequest(Request.Builder builder) throws RequestBodyBuildException; } From 895376ceed404063eca0cb13f04db7012cc1f50e Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 11 Jan 2016 16:06:09 -0300 Subject: [PATCH 09/89] fix typo --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 1e37bc7e..42a3cb2f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ allprojects { - version = 'com.auth0.java' - group = '0.1-SNAPSHOT' + group = 'com.auth0.java' + version = '0.1-SNAPSHOT' repositories { mavenCentral() From dfcc1b18d6f4981e3abdf78a4c2708ca96ae9acf Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Tue, 12 Jan 2016 14:18:25 -0300 Subject: [PATCH 10/89] Add copy constructor, make vars protected, etc Needed for the subclasses in Lock.Android --- .../java/api/internal/RequestFactory.java | 2 +- .../java/com/auth0/java/core/Application.java | 21 ++++++++++++++++--- .../main/java/com/auth0/java/core/Auth0.java | 6 +++--- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java index 96064139..2c5d3860 100644 --- a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java @@ -38,7 +38,7 @@ public class RequestFactory { private static String CLIENT_INFO; - private RequestFactory() {} + protected RequestFactory() {} public static void setClientInfo(String clientInfo) { CLIENT_INFO = clientInfo; diff --git a/core/src/main/java/com/auth0/java/core/Application.java b/core/src/main/java/com/auth0/java/core/Application.java index f9e0814b..8a86b01d 100644 --- a/core/src/main/java/com/auth0/java/core/Application.java +++ b/core/src/main/java/com/auth0/java/core/Application.java @@ -26,6 +26,19 @@ public class Application { private List enterpriseStrategies; private Strategy databaseStrategy; + public Application(Application application) { + id = application.id; + tenant = application.tenant; + authorizeURL = application.authorizeURL; + callbackURL = application.callbackURL; + subscription = application.subscription; + hasAllowedOrigins = application.hasAllowedOrigins; + strategies = application.strategies; + socialStrategies = application.socialStrategies; + enterpriseStrategies = application.enterpriseStrategies; + databaseStrategy = application.databaseStrategy; + } + /** * Creates a new application instance * @param id app id. @@ -173,9 +186,11 @@ public Strategy strategyForName(String name) { * @return a {@link Strategy} */ public Strategy strategyForConnection(Connection connection) { - for (Strategy strategy: this.strategies) { - if (strategy.getConnections().contains(connection)) { - return strategy; + for (Strategy strategy : this.strategies) { + for (Connection conn : strategy.getConnections()) { + if (conn.getName().equals(connection.getName())) { + return strategy; + } } } return null; diff --git a/core/src/main/java/com/auth0/java/core/Auth0.java b/core/src/main/java/com/auth0/java/core/Auth0.java index 05471611..51087b31 100644 --- a/core/src/main/java/com/auth0/java/core/Auth0.java +++ b/core/src/main/java/com/auth0/java/core/Auth0.java @@ -32,9 +32,9 @@ public class Auth0 { private static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; private static final String DOT_AUTH0_DOT_COM = ".auth0.com"; - private final String clientId; - private final String domainUrl; - private final String configurationUrl; + protected final String clientId; + protected final String domainUrl; + protected final String configurationUrl; public Auth0(String clientId, String domain) { this(clientId, domain, null); From 319b0f9a78bb55facf6668296a78f4647cd16c77 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 10:56:48 -0300 Subject: [PATCH 11/89] Remove android Log and Build data --- .../com/auth0/java/api/ParameterBuilder.java | 8 +-- .../main/java/com/auth0/java/api/Request.java | 2 - .../AuthenticationAPIClient.java | 9 ++- .../api/internal/ApplicationInfoRequest.java | 6 +- .../auth0/java/api/internal/BaseRequest.java | 58 ++----------------- .../java/api/internal/SimpleRequest.java | 5 +- .../auth0/java/api/internal/VoidRequest.java | 3 +- .../main/java/com/auth0/java/util/Build.java | 11 ---- .../main/java/com/auth0/java/util/Log.java | 23 -------- 9 files changed, 15 insertions(+), 110 deletions(-) delete mode 100644 core/src/main/java/com/auth0/java/util/Build.java delete mode 100644 core/src/main/java/com/auth0/java/util/Log.java diff --git a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java index 6a4c7b7b..e857edc3 100644 --- a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java @@ -1,6 +1,5 @@ package com.auth0.java.api; -import com.auth0.java.util.Build; import com.auth0.java.util.CheckHelper; import java.util.HashMap; @@ -66,16 +65,11 @@ public ParameterBuilder setConnection(String connection) { } /** - * Sets the 'scope' parameter. If the scope includes 'offline_access', it will set the 'device' parameter. + * Sets the 'scope' parameter. * @param scope a scope value * @return itself */ public ParameterBuilder setScope(String scope) { - if (scope.contains("offline_access")) { - setDevice(Build.MODEL); - } else { - setDevice(null); - } return set("scope", scope); } diff --git a/core/src/main/java/com/auth0/java/api/Request.java b/core/src/main/java/com/auth0/java/api/Request.java index b54e9bbc..5b591afc 100644 --- a/core/src/main/java/com/auth0/java/api/Request.java +++ b/core/src/main/java/com/auth0/java/api/Request.java @@ -33,6 +33,4 @@ public interface Request { void start(BaseCallback callback); - T execute() throws Throwable; - } diff --git a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java index 3921b766..317a4911 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java @@ -33,7 +33,6 @@ import com.auth0.java.core.DatabaseUser; import com.auth0.java.core.Token; import com.auth0.java.core.UserProfile; -import com.auth0.java.util.Log; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -135,7 +134,7 @@ public ParameterizableRequest loginWithResourceOwner() { .asDictionary(); ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) .addParameters(requestParameters); - Log.d(TAG, "Trying to login using " + url.toString() + " with parameters " + requestParameters); + //Log.d(TAG, "Trying to login using " + url.toString() + " with parameters " + requestParameters); return request; } @@ -172,7 +171,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .setAccessToken(token) .asDictionary(); - Log.v(TAG, "Performing OAuth access_token login with parameters " + parameters); + //Log.v(TAG, "Performing OAuth access_token login with parameters " + parameters); final ParameterizableRequest profileRequest = profileRequest(); ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, mapper, Token.class) @@ -224,7 +223,7 @@ public Request tokenInfo(String idToken) { .clearAll() .set(ID_TOKEN_KEY, idToken) .asDictionary(); - Log.d(TAG, "Trying to fetch token with parameters " + requestParameters); + //Log.d(TAG, "Trying to fetch token with parameters " + requestParameters); return profileRequest() .addParameters(requestParameters); } @@ -248,7 +247,7 @@ public ParameterizableRequest createUser(String email, String pass .setConnection(defaultDbConnection) .setClientId(getClientId()) .asDictionary(); - Log.d(TAG, "Creating user with email " + email + " and username " + username); + //Log.d(TAG, "Creating user with email " + email + " and username " + username); return RequestFactory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); } diff --git a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java index 5194bb2e..81839de8 100644 --- a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java @@ -27,7 +27,6 @@ import com.auth0.java.api.APIClientException; import com.auth0.java.api.ParameterizableRequest; import com.auth0.java.core.Application; -import com.auth0.java.util.Log; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; @@ -53,7 +52,7 @@ public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper map @Override protected Request doBuildRequest(Request.Builder builder) { final Request request = builder.build(); - Log.v(TAG, "Fetching application info from " + request.urlString()); + //Log.v(TAG, "Fetching application info from " + request.urlString()); return request; } @@ -87,8 +86,9 @@ public void onResponse(Response response) throws IOException { postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info")); } JSONObject jsonObject = (JSONObject) nextValue; - Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject); + //Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject); Application app = getReader().readValue(jsonObject.toString()); + postOnSuccess(app); } catch (JSONException | IOException e) { postOnFailure(new APIClientException("Failed to parse JSONP", e)); diff --git a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java index 53e0ffa1..a5843773 100644 --- a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java @@ -29,10 +29,6 @@ import com.auth0.java.api.ParameterizableRequest; import com.auth0.java.api.RequestBodyBuildException; import com.auth0.java.api.callback.BaseCallback; -import com.auth0.java.util.Build; -import com.auth0.java.util.Log; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; @@ -40,10 +36,8 @@ import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.Response; import java.io.IOException; -import java.io.InputStream; import java.util.HashMap; import java.util.Map; @@ -53,11 +47,10 @@ abstract class BaseRequest implements ParameterizableRequest, Authorizable private final Map headers; private final Map parameters; - private final HttpUrl url; - private final OkHttpClient client; + protected final HttpUrl url; + protected final OkHttpClient client; private final ObjectReader reader; private final ObjectWriter writer; - protected final ObjectReader errorReader; private BaseCallback callback; @@ -73,9 +66,6 @@ public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, Object this.callback = callback; this.headers = new HashMap<>(); this.parameters = new HashMap<>(); - this.headers.put("User-Agent", String.format("Android %s (%s %s;)", Build.VERSION.RELEASE, Build.MODEL, Build.MANUFACTURER)); - // TODO fix this, pass object mapper as parameter - this.errorReader = new ObjectMapper().reader(new TypeReference>() {}); } protected void setCallback(BaseCallback callback) { @@ -87,7 +77,7 @@ protected void postOnSuccess(final T payload) { } protected final void postOnFailure(final Throwable error) { - Log.e(TAG, "Failed to make request to " + url, error); + //Log.e(TAG, "Failed to make request to " + url, error); this.callback.onFailure(error); } @@ -152,50 +142,10 @@ public void start(BaseCallback callback) { Request request = doBuildRequest(newBuilder()); client.newCall(request).enqueue(this); } catch (RequestBodyBuildException e) { - Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); + //Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); callback.onFailure(new APIClientException("Failed to send request to " + url.toString(), e)); } } - @Override - public T execute() throws Throwable { - Request request; - try { - request = doBuildRequest(newBuilder()); - } catch (RequestBodyBuildException e) { - Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); - throw new APIClientException("Failed to send request to " + url.toString(), e); - } - - Response response; - try { - response = client.newCall(request).execute(); - } catch (IOException e) { - Log.e(TAG, "Request failed to execute", e); - throw new APIClientException("Failed to execute request to " + url.toString(), e); - } - - Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); - final InputStream byteStream = response.body().byteStream(); - if (!response.isSuccessful()) { - Throwable throwable; - try { - Map payload = errorReader.readValue(byteStream); - throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); - } catch (IOException e) { - throwable = new APIClientException("Request failed", response.code(), null); - } - throw throwable; - } - - try { - Log.d(TAG, "Received successful response from " + response.request().urlString()); - T payload = getReader().readValue(byteStream); - return payload; - } catch (IOException e) { - throw new APIClientException("Request failed", response.code(), null); - } - } - protected abstract Request doBuildRequest(Request.Builder builder) throws RequestBodyBuildException; } diff --git a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java index 5efcd57a..89546889 100644 --- a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java @@ -28,7 +28,6 @@ import com.auth0.java.api.ParameterizableRequest; import com.auth0.java.api.Request; import com.auth0.java.api.RequestBodyBuildException; -import com.auth0.java.util.Log; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @@ -64,7 +63,7 @@ public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Stri @Override public void onResponse(Response response) throws IOException { - Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); + //Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable; @@ -79,7 +78,7 @@ public void onResponse(Response response) throws IOException { } try { - Log.d(TAG, "Received successful response from " + response.request().urlString()); + //Log.d(TAG, "Received successful response from " + response.request().urlString()); T payload = getReader().readValue(byteStream); postOnSuccess(payload); } catch (IOException e) { diff --git a/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java index 73d30b53..249bb068 100644 --- a/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java @@ -25,7 +25,6 @@ package com.auth0.java.api.internal; import com.auth0.java.api.APIClientException; -import com.auth0.java.util.Log; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @@ -55,7 +54,7 @@ public VoidRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String @Override public void onResponse(Response response) throws IOException { - Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); + //Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable; diff --git a/core/src/main/java/com/auth0/java/util/Build.java b/core/src/main/java/com/auth0/java/util/Build.java deleted file mode 100644 index 2d61cb2f..00000000 --- a/core/src/main/java/com/auth0/java/util/Build.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.auth0.java.util; - -public class Build { - public static String MANUFACTURER = "MANUFACTURER"; - public static String MODEL = "MODEL"; - public static Version VERSION = new Version(); - - public static class Version { - public static String RELEASE = "RELEASE"; - } -} diff --git a/core/src/main/java/com/auth0/java/util/Log.java b/core/src/main/java/com/auth0/java/util/Log.java deleted file mode 100644 index 18054353..00000000 --- a/core/src/main/java/com/auth0/java/util/Log.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.auth0.java.util; - -public class Log { - public static void d(String tag, String message) { - - } - - public static void e(String tag, String message) { - - } - - public static void e(String tag, String message, Throwable error) { - - } - - public static void v(String tag, String message) { - - } - - public static void w(String tag, String message) { - - } -} From c2621cc8d7d2ecb8e1de8079287bb87d462b1151 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 10:57:25 -0300 Subject: [PATCH 12/89] Add option to set the user agent for all created requests Needed in Lock.Android to set device/version/etc --- .../java/com/auth0/java/api/internal/RequestFactory.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java index 2c5d3860..76f9ea04 100644 --- a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java @@ -37,6 +37,7 @@ public class RequestFactory { private static String CLIENT_INFO; + private static String USER_AGENT; protected RequestFactory() {} @@ -44,6 +45,10 @@ public static void setClientInfo(String clientInfo) { CLIENT_INFO = clientInfo; } + public static void setUserAgent(String userAgent) { + USER_AGENT = userAgent; + } + public static ParameterizableRequest GET(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); } @@ -88,6 +93,9 @@ private static ParameterizableRequest addMetricHeader(ParameterizableRequ if (CLIENT_INFO != null) { request.addHeader("Auth0-Client", CLIENT_INFO); } + if (USER_AGENT != null) { + request.addHeader("User-Agent", USER_AGENT); + } return request; } } From 62a47155a8ce99dca9a46f789541a1a3186ba4f0 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 12:45:24 -0300 Subject: [PATCH 13/89] Add tests --- core/build.gradle | 6 + .../auth0/java/api/ParameterBuilderTest.java | 152 +++++ .../AuthenticationAPIClientTest.java | 570 ++++++++++++++++++ .../java/api/internal/BaseRequestTest.java | 97 +++ .../com/auth0/java/core/ApplicationTest.java | 109 ++++ .../java/com/auth0/java/core/Auth0Test.java | 107 ++++ .../com/auth0/java/core/ConnectionTest.java | 151 +++++ .../com/auth0/java/core/StrategiesTest.java | 43 ++ .../com/auth0/java/core/UserProfileTest.java | 145 +++++ .../auth0/java/util/AuthenticationAPI.java | 174 ++++++ .../util/AuthenticationCallbackMatcher.java | 79 +++ .../com/auth0/java/util/CallbackMatcher.java | 87 +++ .../java/util/MockAuthenticationCallback.java | 76 +++ .../com/auth0/java/util/MockBaseCallback.java | 63 ++ .../java/util/MockRefreshIdTokenCallback.java | 36 ++ 15 files changed, 1895 insertions(+) create mode 100644 core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java create mode 100644 core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java create mode 100644 core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java create mode 100644 core/src/test/java/com/auth0/java/core/ApplicationTest.java create mode 100644 core/src/test/java/com/auth0/java/core/Auth0Test.java create mode 100644 core/src/test/java/com/auth0/java/core/ConnectionTest.java create mode 100644 core/src/test/java/com/auth0/java/core/StrategiesTest.java create mode 100644 core/src/test/java/com/auth0/java/core/UserProfileTest.java create mode 100644 core/src/test/java/com/auth0/java/util/AuthenticationAPI.java create mode 100644 core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java create mode 100644 core/src/test/java/com/auth0/java/util/CallbackMatcher.java create mode 100644 core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java create mode 100644 core/src/test/java/com/auth0/java/util/MockBaseCallback.java create mode 100644 core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java diff --git a/core/build.gradle b/core/build.gradle index 5a26087f..97ff6229 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -8,4 +8,10 @@ dependencies { compile 'org.json:json:20151123' testCompile 'junit:junit:4.12' + testCompile 'org.hamcrest:hamcrest-integration:1.3' + testCompile 'org.hamcrest:hamcrest-core:1.3' + testCompile 'org.hamcrest:hamcrest-library:1.3' + testCompile 'org.mockito:mockito-core:1.10.19' + testCompile 'com.squareup.okhttp:mockwebserver:2.5.0' + testCompile 'com.jayway.awaitility:awaitility:1.6.4' } diff --git a/core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java b/core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java new file mode 100644 index 00000000..24dbfced --- /dev/null +++ b/core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java @@ -0,0 +1,152 @@ +/* + * ParameterBuilderTest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.api; + + +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +public class ParameterBuilderTest { + + public static final String CLIENT_ID = "CLIENT ID"; + public static final String GRANT_TYPE = "password"; + public static final String CONNECTION = "AD"; + public static final String DEVICE = "ANDROID TEST DEVICE"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + private ParameterBuilder builder; + + @Before + public void setUp() throws Exception { + this.builder = ParameterBuilder.newBuilder(); + } + + @Test + public void shouldInstantiateWithNoArguments() throws Exception { + assertThat(new ParameterBuilder(), is(notNullValue())); + assertThat(ParameterBuilder.newBuilder(), is(notNullValue())); + } + + @Test + public void shouldInstantiateWithDefaultScope() throws Exception { + assertThat(new ParameterBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(ParameterBuilder.newBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + } + + @Test + public void shouldInstantiateWithArguments() throws Exception { + assertThat(new ParameterBuilder(new HashMap()), is(notNullValue())); + assertThat(ParameterBuilder.newBuilder(new HashMap()), is(notNullValue())); + } + + @Test + public void shouldFailToInstantiateWithNullParameters() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); + new ParameterBuilder(null); + } + + @Test + public void shouldFailToInstantiateWithNullParametersInFactoryMethod() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); + ParameterBuilder.newBuilder(null); + } + + @Test + public void shouldSetClientID() throws Exception { + assertThat(builder.setClientId(CLIENT_ID).asDictionary(), hasEntry("client_id", CLIENT_ID)); + } + + @Test + public void shouldSetScope() throws Exception { + Map parameters = builder.setScope(ParameterBuilder.SCOPE_OPENID).asDictionary(); + assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); + } + + @Test + public void shouldSetDevice() throws Exception { + Map parameters = builder.setDevice(DEVICE).asDictionary(); + assertThat(parameters, hasEntry("device", DEVICE)); + } + + @Test + public void shouldSetScopeWithOfflineAccess() throws Exception { + Map parameters = builder.setScope(ParameterBuilder.SCOPE_OFFLINE_ACCESS).asDictionary(); + assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + } + + @Test + public void shouldSetGrantType() throws Exception { + assertThat(builder.setGrantType(GRANT_TYPE).asDictionary(), hasEntry("grant_type", GRANT_TYPE)); + } + + @Test + public void shouldSetConnection() throws Exception { + assertThat(builder.setConnection(CONNECTION).asDictionary(), hasEntry("connection", CONNECTION)); + } + + @Test + public void shouldAddArbitraryEntry() throws Exception { + assertThat(builder.set("key", "value").asDictionary(), hasEntry("key", "value")); + } + + @Test + public void shouldAddAllFromDictionary() throws Exception { + Map parameters = new HashMap<>(); + parameters.put("key", "value"); + assertThat(builder.addAll(parameters).asDictionary(), hasEntry("key", "value")); + } + + @Test + public void shouldDoNothingWhenAddingNullParameters() throws Exception { + assertThat(builder.addAll(null).asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + } + + @Test + public void shouldProvideADictionaryCopy() throws Exception { + Map parameters = builder.setClientId(CLIENT_ID).asDictionary(); + parameters.put("key", "value"); + assertThat(builder.asDictionary(), not(hasEntry("key", "value"))); + } + + private static Matcher> hasEntry(String key, Object value) { + return Matchers.hasEntry(key, value); + } +} diff --git a/core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java new file mode 100644 index 00000000..dc871cde --- /dev/null +++ b/core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java @@ -0,0 +1,570 @@ +/* + * AuthenticationAPIClientTest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.api.authentication; + + +import com.auth0.java.api.ParameterBuilder; +import com.auth0.java.core.Application; +import com.auth0.java.core.Auth0; +import com.auth0.java.core.DatabaseUser; +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; +import com.auth0.java.util.AuthenticationAPI; +import com.auth0.java.util.MockAuthenticationCallback; +import com.auth0.java.util.MockBaseCallback; +import com.auth0.java.util.MockRefreshIdTokenCallback; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.mockwebserver.RecordedRequest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import java.util.HashMap; +import java.util.Map; + +import static com.auth0.java.util.AuthenticationAPI.GENERIC_TOKEN; +import static com.auth0.java.util.AuthenticationAPI.ID_TOKEN; +import static com.auth0.java.util.AuthenticationAPI.NEW_ID_TOKEN; +import static com.auth0.java.util.AuthenticationAPI.REFRESH_TOKEN; +import static com.auth0.java.util.AuthenticationCallbackMatcher.hasTokenAndProfile; +import static com.auth0.java.util.CallbackMatcher.hasNoError; +import static com.auth0.java.util.CallbackMatcher.hasNoPayloadOfType; +import static com.auth0.java.util.CallbackMatcher.hasPayload; +import static com.auth0.java.util.CallbackMatcher.hasPayloadOfType; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +public class AuthenticationAPIClientTest { + + private static final String CLIENT_ID = "CLIENTID"; + private static final String DOMAIN = "samples.auth0.com"; + private static final String CONNECTION = "DB"; + + private AuthenticationAPIClient client; + + private AuthenticationAPI mockAPI; + + @Before + public void setUp() throws Exception { + mockAPI = new AuthenticationAPI(); + final String domain = mockAPI.getDomain(); + Auth0 auth0 = new Auth0(CLIENT_ID, domain, domain); + client = new AuthenticationAPIClient(auth0); + } + + @After + public void tearDown() throws Exception { + mockAPI.shutdown(); + } + + @Test + public void shouldCreateClientWithAccountInfo() throws Exception { + AuthenticationAPIClient client = new AuthenticationAPIClient(new Auth0(CLIENT_ID, DOMAIN)); + assertThat(client, is(notNullValue())); + assertThat(client.getClientId(), equalTo(CLIENT_ID)); + assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); + } + + @Test + public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { + mockAPI.willReturnValidApplicationResponse(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + + assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); + assertThat(callback, hasPayloadOfType(Application.class)); + } + + @Test + public void shoulFailWithInvalidJSON() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shoulFailWithInvalidJSONP() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); + final MockBaseCallback callback = new MockBaseCallback<>(); + client.fetchApplicationInfo() + .start(callback); + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shouldFailWithFailedStatusCode() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); + final MockBaseCallback callback = new MockBaseCallback<>(); + + client.fetchApplicationInfo() + .start(callback); + + assertThat(callback, hasNoPayloadOfType(Application.class)); + } + + @Test + public void shouldLoginWithResourceOwner() throws Exception { + mockAPI.willReturnSuccessfulLogin(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection("DB") + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .setScope(ParameterBuilder.SCOPE_OPENID) + .asDictionary(); + client.loginWithResourceOwner() + .addParameters(parameters) + .start(callback); + + assertThat(callback, hasPayloadOfType(Token.class)); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "DB")); + assertThat(body, hasEntry("grant_type", "password")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "notapassword")); + assertThat(body, hasEntry("scope", "openid")); + } + + @Test + public void shouldFailLoginWithResourceOwner() throws Exception { + mockAPI.willReturnFailedLogin(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection(CONNECTION) + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .asDictionary(); + client.loginWithResourceOwner() + .addParameters(parameters) + .start(callback); + + assertThat(callback, hasNoPayloadOfType(Token.class)); + } + + @Test + public void shouldLoginWithUserAndPassword() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + + client.login("support@auth0.com", "voidpassword") + .start(callback); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldFetchTokenInfo() throws Exception { + mockAPI.willReturnTokenInfo(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + client.tokenInfo("ID_TOKEN") + .start(callback); + + assertThat(callback, hasPayloadOfType(UserProfile.class)); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/tokeninfo")); + } + + @Test + public void shouldLoginWithOAuthAccessToken() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithOAuthAccessToken("fbtoken", "facebook") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/access_token")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "facebook")); + assertThat(body, hasEntry("access_token", "fbtoken")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldLoginWithPhoneNumber() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithPhoneNumber("+10101010101", "1234") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "sms")); + assertThat(body, hasEntry("username", "+10101010101")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldLoginWithEmailOnly() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.loginWithEmail("support@auth0.com", "1234") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "email")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldCreateUser() throws Exception { + mockAPI.willReturnSuccessfulSignUp(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.createUser("support@auth0.com", "123123123", "support") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasPayloadOfType(DatabaseUser.class)); + + } + + @Test + public void shouldCreateUserWithoutUsername() throws Exception { + mockAPI.willReturnSuccessfulSignUp(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.createUser("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasPayloadOfType(DatabaseUser.class)); + + } + + @Test + public void shouldSignUpUser() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.signUp("support@auth0.com", "123123123", "support") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldSignUpUserWithoutUsername() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + client.signUp("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasTokenAndProfile()); + } + + @Test + public void shouldChangePassword() throws Exception { + mockAPI.willReturnSuccessfulChangePassword(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.changePassword("support@auth0.com", "123123123") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldCallDelegation() throws Exception { + mockAPI.willReturnGenericDelegationToken(); + + final MockBaseCallback> callback = new MockBaseCallback<>(); + client.delegation() + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + + Map payload = new HashMap<>(); + payload.put("token", GENERIC_TOKEN); + assertThat(callback, hasPayload(payload)); + } + + @Test + public void shouldGetNewIdTokenWithIdToken() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + client.delegationWithIdToken(ID_TOKEN) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("id_token", ID_TOKEN)); + + assertThat(callback, hasPayload(NEW_ID_TOKEN)); + } + + @Test + public void shouldGetNewIdTokenWithRefreshToken() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + client.delegationWithRefreshToken(REFRESH_TOKEN) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); + + assertThat(callback, hasPayload(NEW_ID_TOKEN)); + } + + @Test + public void shouldUnlinkAccount() throws Exception { + mockAPI.willReturnSuccessfulUnlinkAccount(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.unlink("user id", "access token") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/unlink")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("clientID", CLIENT_ID)); + assertThat(body, hasEntry("user_id", "user id")); + assertThat(body, hasEntry("access_token", "access token")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldStartPasswordless() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + final Map parameters = new ParameterBuilder() + .clearAll() + .setConnection("email") + .set("send", "code") + .set("email", "support@auth0.com") + .asDictionary(); + client.passwordless() + .addParameters(parameters) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendEmailCode() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", false) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendEmailLink() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", true) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendSMSCode() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", false) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendSMSLink() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", true) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + + private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { + return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java new file mode 100644 index 00000000..944c9472 --- /dev/null +++ b/core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java @@ -0,0 +1,97 @@ +/* + * BaseRequestTest.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.api.internal; + + +import com.auth0.java.api.RequestBodyBuildException; +import com.auth0.java.api.callback.BaseCallback; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.IOException; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class BaseRequestTest { + + private BaseRequest baseRequest; + + @Mock + private BaseCallback callback; + @Mock + private Throwable throwable; + @Mock + private OkHttpClient client; + @Mock + private ObjectReader reader; + @Mock + private ObjectWriter writer; + @Captor + private ArgumentCaptor captor; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + HttpUrl url = HttpUrl.parse("https://auth0.com"); + baseRequest = new BaseRequest(url, client, reader, writer, callback) { + @Override + public void onResponse(Response response) throws IOException { + + } + + @Override + protected Request doBuildRequest(Request.Builder builder) throws RequestBodyBuildException { + return null; + } + }; + } + + @Test + public void shouldPostOnSuccess() throws Exception { + baseRequest.postOnSuccess("OK"); + verify(callback).onSuccess(eq("OK")); + verifyNoMoreInteractions(callback); + } + + @Test + public void shouldPostOnFailure() throws Exception { + baseRequest.postOnFailure(throwable); + verify(callback).onFailure(eq(throwable)); + verifyNoMoreInteractions(callback); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/java/core/ApplicationTest.java b/core/src/test/java/com/auth0/java/core/ApplicationTest.java new file mode 100644 index 00000000..f8bda589 --- /dev/null +++ b/core/src/test/java/com/auth0/java/core/ApplicationTest.java @@ -0,0 +1,109 @@ +/* + * ApplicationTest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.core; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static com.auth0.java.core.Strategies.ADFS; +import static com.auth0.java.core.Strategies.Auth0; +import static com.auth0.java.core.Strategies.Facebook; +import static com.auth0.java.core.Strategies.Office365; +import static com.auth0.java.core.Strategies.SAMLP; +import static com.auth0.java.core.Strategies.Twitter; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.*; + +public class ApplicationTest { + + public static final String ID = "ID"; + public static final String TENANT = "TENANT"; + public static final String AUTHORIZE_URL = "AUTHORIZE"; + public static final String CALLBACK_URL = "CALLBACK"; + public static final String SUBSCRIPTION = "SUBSCRIPTION"; + public static final boolean HAS_ALLOWED_ORIGINS = true; + + @Test + public void shouldInstantiateApplication() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application, is(notNullValue())); + } + + @Test + public void shouldHaveApplicationInfo() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application.getId(), equalTo(ID)); + assertThat(application.getTenant(), equalTo(TENANT)); + assertThat(application.getAuthorizeURL(), equalTo(AUTHORIZE_URL)); + assertThat(application.getCallbackURL(), equalTo(CALLBACK_URL)); + assertThat(application.getSubscription(), equalTo(SUBSCRIPTION)); + assertThat(application.isHasAllowedOrigins(), equalTo(HAS_ALLOWED_ORIGINS)); + } + + @Test + public void shouldReturnDatabaseStrategy() throws Exception { + Application application = newApplicationWithStrategies(Auth0); + assertThat(application.getDatabaseStrategy(), is(notNullValue())); + assertThat(application.getDatabaseStrategy().getName(), equalTo(Auth0.getName())); + } + + @Test + public void shouldReturnNoDatabaseStrategy() throws Exception { + Application application = newApplicationWithStrategies(Facebook); + assertThat(application.getDatabaseStrategy(), is(nullValue())); + } + + @Test + public void shouldReturnSocialStrategies() throws Exception { + Application application = newApplicationWithStrategies(Facebook, Twitter, Auth0); + assertThat(application.getSocialStrategies().size(), equalTo(2)); + } + + @Test + public void shouldReturnEnterpriseStrategies() throws Exception { + Application application = newApplicationWithStrategies(Auth0, ADFS, SAMLP, Office365); + assertThat(application.getEnterpriseStrategies().size(), equalTo(3)); + } + + private static Strategy newStrategyFor(Strategies strategyMetadata) { + return new Strategy(strategyMetadata.getName(), Arrays.asList(mock(Connection.class))); + } + + private static Application newApplicationWithStrategies(Strategies... list) { + List strategies = new ArrayList<>(); + for (Strategies str: list) { + strategies.add(newStrategyFor(str)); + } + Application application = new Application(ID, TENANT, AUTHORIZE_URL, CALLBACK_URL, SUBSCRIPTION, HAS_ALLOWED_ORIGINS, strategies); + return application; + } +} diff --git a/core/src/test/java/com/auth0/java/core/Auth0Test.java b/core/src/test/java/com/auth0/java/core/Auth0Test.java new file mode 100644 index 00000000..3a78830e --- /dev/null +++ b/core/src/test/java/com/auth0/java/core/Auth0Test.java @@ -0,0 +1,107 @@ +/* + * Auth0Test.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.core; + +import com.auth0.java.api.authentication.AuthenticationAPIClient; + +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.*; + +public class Auth0Test { + + private static final String CLIENT_ID = "CLIENT_ID"; + private static final String DOMAIN = "samples.auth0.com"; + private static final String CONFIG_DOMAIN_CUSTOM = "config.mydomain.com"; + private static final String EU_DOMAIN = "samples.eu.auth0.com"; + private static final String AU_DOMAIN = "samples.au.auth0.com"; + private static final String OTHER_DOMAIN = "samples-test.other-subdomain.other.auth0.com"; + + @Test + public void shouldBuildWithClientIdAndDomain() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.auth0.com")); + } + + @Test + public void shouldBuildWithConfigurationDomainToo() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN, CONFIG_DOMAIN_CUSTOM); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://config.mydomain.com")); + } + + @Test + public void shouldHandleEUInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, EU_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.eu.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.eu.auth0.com")); + } + + @Test + public void shouldHandleAUInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, AU_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples.au.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.au.auth0.com")); + } + + @Test + public void shouldHandleOtherInstance() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, OTHER_DOMAIN); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://samples-test.other-subdomain.other.auth0.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://cdn.other.auth0.com")); + } + + @Test + public void shouldHandleNonAuth0Domain() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, "mydomain.com"); + assertThat(auth0.getClientId(), equalTo(CLIENT_ID)); + assertThat(auth0.getDomainUrl(), equalTo("https://mydomain.com")); + assertThat(auth0.getConfigurationUrl(), equalTo("https://mydomain.com")); + } + + @Test + public void shouldBuildNewClient() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + AuthenticationAPIClient client = auth0.newAuthenticationAPIClient(); + assertThat(client, is(notNullValue())); + assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); + assertThat(client.getClientId(), equalTo(CLIENT_ID)); + } + + @Test + public void shouldReturnAuthorizeUrl() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + assertThat(auth0.getAuthorizeUrl(), equalTo("https://samples.auth0.com/authorize")); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/auth0/java/core/ConnectionTest.java b/core/src/test/java/com/auth0/java/core/ConnectionTest.java new file mode 100644 index 00000000..b8d11dfd --- /dev/null +++ b/core/src/test/java/com/auth0/java/core/ConnectionTest.java @@ -0,0 +1,151 @@ +/* + * ConnectionTest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.core; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +public class ConnectionTest { + + public static final String CONNECTION_NAME = "Username-Password"; + public static final Object VALUE = "value"; + public static final String KEY = "key"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void shouldBuildConnectionWithName() { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertNotNull(connection); + assertThat(connection.getName(), equalTo(CONNECTION_NAME)); + } + + @Test + public void shouldBuildConnectionWithValues() { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + assertThat(connection.getValues(), hasEntry(KEY, VALUE)); + } + + @Test + public void shouldNotStoreNameInValues() throws Exception { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertThat(connection.getValues(), not(hasKey("name"))); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldRaiseExceptionWhenNameIsNull() { + Map values = null; + new Connection(values); + } + + @Test + public void shouldReturnValueFromKey() { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + String value = connection.getValueForKey(KEY); + assertThat(value, equalTo(VALUE)); + } + + @Test + public void shouldReturnBooleanValueFromKey() { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put(KEY, true); + Connection connection = new Connection(values); + boolean value = connection.booleanForKey(KEY); + assertThat(value, is(true)); + } + + @Test + public void shouldReturnDefaultBooleanValueFromKey() { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + boolean value = connection.booleanForKey(KEY); + assertThat(value, is(false)); + } + + @Test + public void shouldRaiseExceptionWhenValueIsNotBoolean() { + expectedException.expect(ClassCastException.class); + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put(KEY, VALUE); + Connection connection = new Connection(values); + connection.booleanForKey(KEY); + } + + @Test + public void shouldReturnDomainNameInSet() throws Exception { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put("domain", "domain.com"); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet(), hasItem("domain.com")); + } + + @Test + public void shouldReturnAllDomainNamesAsSet() throws Exception { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + values.put("domain", "domain.com"); + values.put("domain_aliases", Arrays.asList("domain2.com", "domain3.com")); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet(), hasItems("domain.com", "domain2.com", "domain3.com")); + } + + @Test + public void shouldReturnEmptySetWithNoDomainName() throws Exception { + Map values = new HashMap<>(); + values.put("name", CONNECTION_NAME); + Connection connection = new Connection(values); + assertThat(connection.getDomainSet().isEmpty(), is(true)); + } +} diff --git a/core/src/test/java/com/auth0/java/core/StrategiesTest.java b/core/src/test/java/com/auth0/java/core/StrategiesTest.java new file mode 100644 index 00000000..555d8d1b --- /dev/null +++ b/core/src/test/java/com/auth0/java/core/StrategiesTest.java @@ -0,0 +1,43 @@ +/* + * StrategiesTest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.core; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class StrategiesTest { + @Test + public void shouldReturnUnknownSocial() { + Strategies unknownSocial = Strategies.fromName("this-strategy-does-not-exist"); + assertEquals(unknownSocial.getType(), Strategies.Type.SOCIAL); + } + + @Test + public void shouldReturnValidDatabaseStrategy() { + Strategies auth0Database = Strategies.fromName("auth0"); + assertEquals(auth0Database.getType(), Strategies.Type.DATABASE); + } +} diff --git a/core/src/test/java/com/auth0/java/core/UserProfileTest.java b/core/src/test/java/com/auth0/java/core/UserProfileTest.java new file mode 100644 index 00000000..f4dd7203 --- /dev/null +++ b/core/src/test/java/com/auth0/java/core/UserProfileTest.java @@ -0,0 +1,145 @@ +/* + * UserProfileTest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.core; + + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + + +public class UserProfileTest { + + public static final String USER_ID = "IOU a user id"; + public static final String NAME = "Somebody Someone"; + public static final String NICKNAME = "somebody"; + public static final String EMAIL = "somebody@somwhere.com"; + public static final String CREATED_AT = "2014-07-06T18:33:49.005Z"; + public static final String PICTURE_URL = "http://somewhere.com/pic.jpg"; + public static final Object EXTRA_VALUE = "extra_value"; + public static final long CREATED_AT_TIMESTAMP = 1404671629005l; + public static final String FACEBOOK = "facebook"; + public static final String TOKEN = "token"; + public static final String SECRET = "secret"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void shouldRaiseExceptionWithNullValuesWhenCreatingInstance() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalTo("must supply non-null values")); + new UserProfile((HashMap)null); + } + + @Test + public void shouldRaiseExceptionWithNoUserIdWhenCreatingInstance() throws Exception { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage(equalTo("profile must have a user id")); + new UserProfile(new HashMap()); + } + + @Test + public void shouldInstantiateProfileWithId() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + } + + @Test + public void shouldInstantiateWithBasicProfileInfo() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + values.put("name", NAME); + values.put("nickname", NICKNAME); + values.put("email", EMAIL); + values.put("picture", PICTURE_URL); + values.put("created_at", CREATED_AT); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getName(), equalTo(NAME)); + assertThat(profile.getNickname(), equalTo(NICKNAME)); + assertThat(profile.getEmail(), equalTo(EMAIL)); + assertThat(profile.getPictureURL(), equalTo(PICTURE_URL)); + assertThat(profile.getCreatedAt().getTime(), equalTo(CREATED_AT_TIMESTAMP)); + assertThat(profile.getExtraInfo().size(), equalTo(0)); + } + + @Test + public void shouldHandleExtraProfileInfo() throws Exception { + Map values = new HashMap(); + values.put("user_id", USER_ID); + values.put("extra_key", EXTRA_VALUE); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getExtraInfo(), hasEntry("extra_key", EXTRA_VALUE)); + } + + @Test + public void shouldHandleIdentities() throws Exception { + Map values = new HashMap(); + Map identityValue = new HashMap<>(); + Map profileData = new HashMap<>(); + identityValue.put("user_id", USER_ID); + identityValue.put("connection", FACEBOOK); + identityValue.put("provider", FACEBOOK); + identityValue.put("isSocial", true); + identityValue.put("access_token", TOKEN); + identityValue.put("access_token_secret", SECRET); + identityValue.put("profileData", profileData); + profileData.put("name", "John Doe"); + + values.put("user_id", USER_ID); + values.put("identities", Collections.singletonList(identityValue)); + UserProfile profile = new UserProfile(values); + assertValidProfile(profile); + assertThat(profile.getIdentities(), hasSize(1)); + UserIdentity identity = profile.getIdentities().get(0); + assertThat(identity, isA(UserIdentity.class)); + assertThat(identity.getId(), equalTo(USER_ID)); + assertThat(identity.getProvider(), equalTo(FACEBOOK)); + assertThat(identity.getConnection(), equalTo(FACEBOOK)); + assertThat(identity.getAccessToken(), equalTo(TOKEN)); + assertThat(identity.getAccessTokenSecret(), equalTo(SECRET)); + } + + private void assertValidProfile(UserProfile profile) { + assertThat(profile, is(notNullValue())); + assertThat(profile.getId(), equalTo(USER_ID)); + } +} diff --git a/core/src/test/java/com/auth0/java/util/AuthenticationAPI.java b/core/src/test/java/com/auth0/java/util/AuthenticationAPI.java new file mode 100644 index 00000000..b7be51d5 --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/AuthenticationAPI.java @@ -0,0 +1,174 @@ +/* + * AuthenticationAPI.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; + +import java.io.IOException; + +public class AuthenticationAPI { + + public static final String REFRESH_TOKEN = "REFRESH_TOKEN"; + public static final String ID_TOKEN = "ID_TOKEN"; + public static final String ACCESS_TOKEN = "ACCESS_TOKEN"; + public static final String BEARER = "BEARER"; + public static final String GENERIC_TOKEN = "GENERIC_TOKEN"; + public static final String NEW_ID_TOKEN = "NEW_ID_TOKEN"; + public static final int EXPIRES_IN = 1234567890; + public static final String TOKEN_TYPE = "TOKEN_TYPE"; + + private MockWebServer server; + + public AuthenticationAPI() throws IOException { + this.server = new MockWebServer(); + this.server.start(); + } + + public String getDomain() { + return server.url("/").toString(); + } + + public void shutdown() throws IOException { + this.server.shutdown(); + } + + public RecordedRequest takeRequest() throws InterruptedException { + return server.takeRequest(); + } + + public AuthenticationAPI willReturnValidApplicationResponse() { + return willReturnApplicationResponseWithBody("Auth0.setClient({\"id\":\"CLIENTID\",\"tenant\":\"overmind\",\"subscription\":\"free\",\"authorize\":\"https://samples.auth0.com/authorize\",\"callback\":\"http://localhost:3000/\",\"hasAllowedOrigins\":true,\"strategies\":[{\"name\":\"twitter\",\"connections\":[{\"name\":\"twitter\"}]}]});", 200); + } + + public AuthenticationAPI willReturnSuccessfulChangePassword() { + server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulUnlinkAccount() { + server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)); + return this; + } + + public AuthenticationAPI willReturnGenericDelegationToken() { + String json = "{\n" + + " \"token\": \"" + GENERIC_TOKEN + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulPasswordlessStart() { + String json = "{\n" + + " \"phone+number\": \"+1098098098\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnNewIdToken() { + String json = "{\n" + + " \"id_token\": \"" + NEW_ID_TOKEN + "\",\n" + + " \"expires_in\": " + EXPIRES_IN + ",\n" + + " \"token_type\": \"" + TOKEN_TYPE + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulSignUp() { + String json = "{\n" + + " \"_id\": \"gjsmgdkjs72jljsf2dsdhh\", \n" + + " \"email\": \"support@auth0.com\", \n" + + " \"email_verified\": false, \n" + + " \"username\": \"support\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnSuccessfulLogin() { + String json = "{\n" + + " \"refresh_token\": \"" + REFRESH_TOKEN + "\",\n" + + " \"id_token\": \"" + ID_TOKEN + "\",\n" + + " \"access_token\": \"" + ACCESS_TOKEN + "\",\n" + + " \"token_type\": \"" + BEARER + "\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnFailedLogin() { + String json = "{\n" + + " \"error\": \"invalid_request\",\n" + + " \"error_description\": \"a random error\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 400)); + return this; + } + + public AuthenticationAPI willReturnTokenInfo() { + String json = "{\n" + + " \"email\": \"p@p.xom\",\n" + + " \"email_verified\": false,\n" + + " \"picture\": \"https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png\",\n" + + " \"user_id\": \"auth0|53b995f8bce68d9fc900099c\",\n" + + " \"name\": \"p@p.xom\",\n" + + " \"nickname\": \"p\",\n" + + " \"identities\": [\n" + + " {\n" + + " \"user_id\": \"53b995f8bce68d9fc900099c\",\n" + + " \"provider\": \"auth0\",\n" + + " \"connection\": \"Username-Password-Authentication\",\n" + + " \"isSocial\": false\n" + + " }\n" + + " ],\n" + + " \"created_at\": \"2014-07-06T18:33:49.005Z\",\n" + + " \"username\": \"p\",\n" + + " \"updated_at\": \"2015-09-30T19:43:48.499Z\"\n" + + "}"; + server.enqueue(responseWithJSON(json, 200)); + return this; + } + + public AuthenticationAPI willReturnApplicationResponseWithBody(String body, int statusCode) { + MockResponse response = new MockResponse() + .setResponseCode(statusCode) + .addHeader("Content-Type", "application/x-javascript") + .setBody(body); + server.enqueue(response); + return this; + } + + private MockResponse responseWithJSON(String json, int statusCode) { + return new MockResponse() + .setResponseCode(statusCode) + .addHeader("Content-Type", "application/json") + .setBody(json); + } + +} diff --git a/core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java b/core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java new file mode 100644 index 00000000..9db17864 --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java @@ -0,0 +1,79 @@ +/* + * AuthenticationCallbackMatcher.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; +import com.jayway.awaitility.core.ConditionTimeoutException; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +import static com.jayway.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +public class AuthenticationCallbackMatcher extends BaseMatcher { + + private final Matcher tokenMatcher; + private final Matcher profileMatcher; + private final Matcher errorMatcher; + + public AuthenticationCallbackMatcher(Matcher tokenMatcher, Matcher profileMatcher, Matcher errorMatcher) { + this.tokenMatcher = tokenMatcher; + this.profileMatcher = profileMatcher; + this.errorMatcher = errorMatcher; + } + + @Override + public boolean matches(Object item) { + MockAuthenticationCallback callback = (MockAuthenticationCallback) item; + try { + await().until(callback.token(), tokenMatcher); + await().until(callback.profile(), profileMatcher); + await().until(callback.error(), errorMatcher); + return true; + } catch (ConditionTimeoutException e) { + return false; + } + } + + @Override + public void describeTo(Description description) { + description + .appendText("successful method be called"); + } + + public static Matcher hasTokenAndProfile() { + return new AuthenticationCallbackMatcher(is(notNullValue(Token.class)), is(notNullValue(UserProfile.class)), is(nullValue(Throwable.class))); + } + + public static Matcher hasNeitherTokeNorProfile() { + return new AuthenticationCallbackMatcher(is(nullValue(Token.class)), is(nullValue(UserProfile.class)), is(notNullValue(Throwable.class))); + } + +} diff --git a/core/src/test/java/com/auth0/java/util/CallbackMatcher.java b/core/src/test/java/com/auth0/java/util/CallbackMatcher.java new file mode 100644 index 00000000..10ea662c --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/CallbackMatcher.java @@ -0,0 +1,87 @@ +/* + * CallbackMatcher.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.jayway.awaitility.core.ConditionTimeoutException; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +import static com.jayway.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isA; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +public class CallbackMatcher extends BaseMatcher> { + private final Matcher payloadMatcher; + private final Matcher errorMatcher; + + public CallbackMatcher( Matcher payloadMatcher, Matcher errorMatcher) { + this.payloadMatcher = payloadMatcher; + this.errorMatcher = errorMatcher; + } + + @Override + @SuppressWarnings("unchecked") + public boolean matches(Object item) { + MockBaseCallback callback = (MockBaseCallback) item; + try { + await().until(callback.payload(), payloadMatcher); + await().until(callback.error(), errorMatcher); + return true; + } catch (ConditionTimeoutException e) { + return false; + } + } + + @Override + public void describeTo(Description description) { + description + .appendText("successful method be called"); + } + + public static Matcher> hasPayloadOfType(Class clazz) { + return new CallbackMatcher<>(isA(clazz), is(nullValue(Throwable.class))); + } + + public static Matcher> hasPayload(T payload) { + return new CallbackMatcher<>(equalTo(payload), is(nullValue(Throwable.class))); + } + + public static Matcher> hasNoPayloadOfType(Class clazz) { + return new CallbackMatcher<>(is(nullValue(clazz)), is(notNullValue(Throwable.class))); + } + + public static Matcher> hasNoError() { + return new CallbackMatcher<>(is(nullValue(Void.class)), is(nullValue(Throwable.class))); + } + + public static Matcher> hasError() { + return new CallbackMatcher<>(is(nullValue(Void.class)), is(notNullValue(Throwable.class))); + } +} diff --git a/core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java b/core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java new file mode 100644 index 00000000..3178ec75 --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java @@ -0,0 +1,76 @@ +/* + * MockAuthenticationCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.auth0.java.api.callback.AuthenticationCallback; +import com.auth0.java.core.Token; +import com.auth0.java.core.UserProfile; + +import java.util.concurrent.Callable; + +public class MockAuthenticationCallback implements AuthenticationCallback { + + private Token token; + private UserProfile profile; + private Throwable error; + + @Override + public void onSuccess(UserProfile profile, Token token) { + this.token = token; + this.profile = profile; + } + + @Override + public void onFailure(Throwable error) { + this.error = error; + } + + public Callable token() { + return new Callable() { + @Override + public Token call() throws Exception { + return token; + } + }; + } + + public Callable profile() { + return new Callable() { + @Override + public UserProfile call() throws Exception { + return profile; + } + }; + } + + public Callable error() { + return new Callable() { + @Override + public Throwable call() throws Exception { + return error; + } + }; + } +} diff --git a/core/src/test/java/com/auth0/java/util/MockBaseCallback.java b/core/src/test/java/com/auth0/java/util/MockBaseCallback.java new file mode 100644 index 00000000..03d0f0ba --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/MockBaseCallback.java @@ -0,0 +1,63 @@ +/* + * MockBaseCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.auth0.java.api.callback.BaseCallback; + +import java.util.concurrent.Callable; + +public class MockBaseCallback implements BaseCallback { + + private T payload; + private Throwable error; + + @Override + public void onSuccess(T payload) { + this.payload = payload; + } + + @Override + public void onFailure(Throwable error) { + this.error = error; + } + + public Callable payload() { + return new Callable() { + @Override + public T call() throws Exception { + return payload; + } + }; + } + + public Callable error() { + return new Callable() { + @Override + public Throwable call() throws Exception { + return error; + } + }; + } +} diff --git a/core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java b/core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java new file mode 100644 index 00000000..dd2b7bc9 --- /dev/null +++ b/core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java @@ -0,0 +1,36 @@ +/* + * MockRefreshIdTokenCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.java.util; + +import com.auth0.java.api.callback.RefreshIdTokenCallback; + +public class MockRefreshIdTokenCallback extends MockBaseCallback implements RefreshIdTokenCallback { + + @Override + public void onSuccess(String idToken, String tokenType, int expiresIn) { + onSuccess(idToken); + } + +} From d826f6964347ab91549084c8792f4626aaaec830 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 13:52:37 -0300 Subject: [PATCH 14/89] Add/fix copyright --- .../auth0/java/api/AuthorizableRequest.java | 2 +- .../com/auth0/java/api/ParameterBuilder.java | 24 +++++++++++++++++++ .../java/api/ParameterizableRequest.java | 2 +- .../java/api/RequestBodyBuildException.java | 24 +++++++++++++++++++ .../AuthenticationAPIClient.java | 2 +- .../api/callback/AuthenticationCallback.java | 24 +++++++++++++++++++ .../auth0/java/api/callback/BaseCallback.java | 24 +++++++++++++++++++ .../com/auth0/java/api/callback/Callback.java | 24 +++++++++++++++++++ .../auth0/java/api/internal/BaseRequest.java | 2 +- .../java/api/internal/SimpleRequest.java | 2 +- .../java/com/auth0/java/core/Application.java | 24 +++++++++++++++++++ .../java/com/auth0/java/core/Connection.java | 24 +++++++++++++++++++ .../java/com/auth0/java/core/Strategies.java | 24 +++++++++++++++++++ .../java/com/auth0/java/core/Strategy.java | 24 +++++++++++++++++++ .../main/java/com/auth0/java/core/Token.java | 24 +++++++++++++++++++ .../com/auth0/java/core/UserIdentity.java | 24 +++++++++++++++++++ .../java/com/auth0/java/core/UserProfile.java | 24 +++++++++++++++++++ .../java/com/auth0/java/util/CheckHelper.java | 2 +- 18 files changed, 294 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java b/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java index 33b2586c..b2700724 100644 --- a/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java +++ b/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java @@ -1,5 +1,5 @@ /* - * AuthorizedRequest.java + * AuthorizableRequest.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * diff --git a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java index e857edc3..50b924c0 100644 --- a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/java/api/ParameterBuilder.java @@ -1,3 +1,27 @@ +/* + * ParameterBuilder.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.api; import com.auth0.java.util.CheckHelper; diff --git a/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java b/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java index de9fb199..80ac1b47 100644 --- a/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java +++ b/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java @@ -1,5 +1,5 @@ /* - * Parameterizable.java + * ParameterizableRequest.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * diff --git a/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java index 43a81c14..4cd1c2f8 100644 --- a/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java +++ b/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java @@ -1,3 +1,27 @@ +/* + * RequestBodyBuildException.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.api; /** diff --git a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java index 317a4911..a7487f48 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java @@ -1,5 +1,5 @@ /* - * AuthenticationClient.java + * AuthenticationAPIClient.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * diff --git a/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java b/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java index 5698725d..b508a964 100644 --- a/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java +++ b/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java @@ -1,3 +1,27 @@ +/* + * AuthenticationCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.api.callback; import com.auth0.java.core.Token; diff --git a/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java b/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java index d0fedc29..34563662 100644 --- a/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java +++ b/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java @@ -1,3 +1,27 @@ +/* + * BaseCallback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.api.callback; /** diff --git a/core/src/main/java/com/auth0/java/api/callback/Callback.java b/core/src/main/java/com/auth0/java/api/callback/Callback.java index eb04de94..35df298e 100644 --- a/core/src/main/java/com/auth0/java/api/callback/Callback.java +++ b/core/src/main/java/com/auth0/java/api/callback/Callback.java @@ -1,3 +1,27 @@ +/* + * Callback.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.api.callback; /** diff --git a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java index a5843773..1d71266f 100644 --- a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java @@ -1,5 +1,5 @@ /* - * ResponseCallbackTask.java + * BaseRequest.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * diff --git a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java index 89546889..6e4da124 100644 --- a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java @@ -1,5 +1,5 @@ /* - * AuthenticationRequest.java + * SimpleRequest.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * diff --git a/core/src/main/java/com/auth0/java/core/Application.java b/core/src/main/java/com/auth0/java/core/Application.java index 8a86b01d..7ec16ccc 100644 --- a/core/src/main/java/com/auth0/java/core/Application.java +++ b/core/src/main/java/com/auth0/java/core/Application.java @@ -1,3 +1,27 @@ +/* + * Application.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/core/src/main/java/com/auth0/java/core/Connection.java b/core/src/main/java/com/auth0/java/core/Connection.java index 799b593a..df7c5b9f 100644 --- a/core/src/main/java/com/auth0/java/core/Connection.java +++ b/core/src/main/java/com/auth0/java/core/Connection.java @@ -1,3 +1,27 @@ +/* + * Connection.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.auth0.java.util.CheckHelper; diff --git a/core/src/main/java/com/auth0/java/core/Strategies.java b/core/src/main/java/com/auth0/java/core/Strategies.java index a7aff139..408d6f57 100644 --- a/core/src/main/java/com/auth0/java/core/Strategies.java +++ b/core/src/main/java/com/auth0/java/core/Strategies.java @@ -1,3 +1,27 @@ +/* + * Strategies.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import static com.auth0.java.core.Strategies.Type.DATABASE; diff --git a/core/src/main/java/com/auth0/java/core/Strategy.java b/core/src/main/java/com/auth0/java/core/Strategy.java index 0d64ed0d..bdfbfb2e 100644 --- a/core/src/main/java/com/auth0/java/core/Strategy.java +++ b/core/src/main/java/com/auth0/java/core/Strategy.java @@ -1,3 +1,27 @@ +/* + * Strategy.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/core/src/main/java/com/auth0/java/core/Token.java b/core/src/main/java/com/auth0/java/core/Token.java index 79868369..91b64e00 100644 --- a/core/src/main/java/com/auth0/java/core/Token.java +++ b/core/src/main/java/com/auth0/java/core/Token.java @@ -1,3 +1,27 @@ +/* + * Token.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/java/core/UserIdentity.java b/core/src/main/java/com/auth0/java/core/UserIdentity.java index 1ae2c994..58add634 100644 --- a/core/src/main/java/com/auth0/java/core/UserIdentity.java +++ b/core/src/main/java/com/auth0/java/core/UserIdentity.java @@ -1,3 +1,27 @@ +/* + * UserIdentity.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/core/src/main/java/com/auth0/java/core/UserProfile.java b/core/src/main/java/com/auth0/java/core/UserProfile.java index 957b4f99..1ccf3921 100644 --- a/core/src/main/java/com/auth0/java/core/UserProfile.java +++ b/core/src/main/java/com/auth0/java/core/UserProfile.java @@ -1,3 +1,27 @@ +/* + * UserProfile.java + * + * Copyright (c) 2015 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + package com.auth0.java.core; import com.auth0.java.util.CheckHelper; diff --git a/core/src/main/java/com/auth0/java/util/CheckHelper.java b/core/src/main/java/com/auth0/java/util/CheckHelper.java index 19ce912e..e6e14941 100644 --- a/core/src/main/java/com/auth0/java/util/CheckHelper.java +++ b/core/src/main/java/com/auth0/java/util/CheckHelper.java @@ -1,5 +1,5 @@ /* - * Preconditions.java + * CheckHelper.java * * Copyright (c) 2015 Auth0 (http://auth0.com) * From 01ccfcb2f42e39f98ab4621ef7660b2d745e4965 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 14:36:29 -0300 Subject: [PATCH 15/89] Update package namespaces --- build.gradle | 4 +- .../auth0/{java/core => }/Application.java | 4 +- .../java/com/auth0/{java/core => }/Auth0.java | 4 +- .../com/auth0/{java/core => }/Connection.java | 4 +- .../auth0/{java/core => }/DatabaseUser.java | 2 +- .../com/auth0/{java/core => }/Strategies.java | 10 ++-- .../com/auth0/{java/core => }/Strategy.java | 2 +- .../java/com/auth0/{java/core => }/Token.java | 2 +- .../auth0/{java/core => }/UserIdentity.java | 2 +- .../auth0/{java/core => }/UserProfile.java | 4 +- .../AuthenticationAPIClient.java | 24 +++++----- .../authentication/AuthenticationRequest.java | 14 +++--- .../authentication/DelegationRequest.java | 8 ++-- .../authentication/SignUpRequest.java | 10 ++-- .../api/APIClientException.java | 2 +- .../api/AuthorizableRequest.java | 2 +- .../api/ParameterBuilder.java | 4 +- .../api/ParameterizableRequest.java | 2 +- .../{java => authentication}/api/Request.java | 4 +- .../api/RequestBodyBuildException.java | 2 +- .../api/callback/AuthenticationCallback.java | 6 +-- .../api/callback/BaseCallback.java | 2 +- .../api/callback/Callback.java | 2 +- .../api/callback/RefreshIdTokenCallback.java | 2 +- .../api/internal/ApplicationInfoRequest.java | 8 ++-- .../api/internal/BaseRequest.java | 12 ++--- .../api/internal/JsonRequestBodyBuilder.java | 4 +- .../api/internal/RequestFactory.java | 10 ++-- .../api/internal/SimpleRequest.java | 10 ++-- .../api/internal/VoidRequest.java | 4 +- .../api}/util/CheckHelper.java | 2 +- .../{java/core => }/ApplicationTest.java | 19 +++++--- .../com/auth0/{java/core => }/Auth0Test.java | 4 +- .../auth0/{java/core => }/ConnectionTest.java | 4 +- .../auth0/{java/core => }/StrategiesTest.java | 4 +- .../{java/core => }/UserProfileTest.java | 5 +- .../AuthenticationAPIClientTest.java | 47 +++++++++---------- .../api/ParameterBuilderTest.java | 2 +- .../api/internal/BaseRequestTest.java | 6 +-- .../api}/util/AuthenticationAPI.java | 2 +- .../util/AuthenticationCallbackMatcher.java | 6 +-- .../api}/util/CallbackMatcher.java | 2 +- .../api}/util/MockAuthenticationCallback.java | 8 ++-- .../api}/util/MockBaseCallback.java | 4 +- .../api}/util/MockRefreshIdTokenCallback.java | 4 +- 45 files changed, 149 insertions(+), 140 deletions(-) rename core/src/main/java/com/auth0/{java/core => }/Application.java (98%) rename core/src/main/java/com/auth0/{java/core => }/Auth0.java (97%) rename core/src/main/java/com/auth0/{java/core => }/Connection.java (98%) rename core/src/main/java/com/auth0/{java/core => }/DatabaseUser.java (98%) rename core/src/main/java/com/auth0/{java/core => }/Strategies.java (93%) rename core/src/main/java/com/auth0/{java/core => }/Strategy.java (98%) rename core/src/main/java/com/auth0/{java/core => }/Token.java (98%) rename core/src/main/java/com/auth0/{java/core => }/UserIdentity.java (99%) rename core/src/main/java/com/auth0/{java/core => }/UserProfile.java (98%) rename core/src/main/java/com/auth0/{java/api => }/authentication/AuthenticationAPIClient.java (97%) rename core/src/main/java/com/auth0/{java/api => }/authentication/AuthenticationRequest.java (92%) rename core/src/main/java/com/auth0/{java/api => }/authentication/DelegationRequest.java (92%) rename core/src/main/java/com/auth0/{java/api => }/authentication/SignUpRequest.java (93%) rename core/src/main/java/com/auth0/{java => authentication}/api/APIClientException.java (98%) rename core/src/main/java/com/auth0/{java => authentication}/api/AuthorizableRequest.java (97%) rename core/src/main/java/com/auth0/{java => authentication}/api/ParameterBuilder.java (98%) rename core/src/main/java/com/auth0/{java => authentication}/api/ParameterizableRequest.java (97%) rename core/src/main/java/com/auth0/{java => authentication}/api/Request.java (93%) rename core/src/main/java/com/auth0/{java => authentication}/api/RequestBodyBuildException.java (97%) rename core/src/main/java/com/auth0/{java => authentication}/api/callback/AuthenticationCallback.java (93%) rename core/src/main/java/com/auth0/{java => authentication}/api/callback/BaseCallback.java (96%) rename core/src/main/java/com/auth0/{java => authentication}/api/callback/Callback.java (96%) rename core/src/main/java/com/auth0/{java => authentication}/api/callback/RefreshIdTokenCallback.java (97%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/ApplicationInfoRequest.java (95%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/BaseRequest.java (93%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/JsonRequestBodyBuilder.java (94%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/RequestFactory.java (94%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/SimpleRequest.java (93%) rename core/src/main/java/com/auth0/{java => authentication}/api/internal/VoidRequest.java (96%) rename core/src/main/java/com/auth0/{java => authentication/api}/util/CheckHelper.java (97%) rename core/src/test/java/com/auth0/{java/core => }/ApplicationTest.java (91%) rename core/src/test/java/com/auth0/{java/core => }/Auth0Test.java (98%) rename core/src/test/java/com/auth0/{java/core => }/ConnectionTest.java (99%) rename core/src/test/java/com/auth0/{java/core => }/StrategiesTest.java (97%) rename core/src/test/java/com/auth0/{java/core => }/UserProfileTest.java (98%) rename core/src/test/java/com/auth0/{java/api => }/authentication/AuthenticationAPIClientTest.java (94%) rename core/src/test/java/com/auth0/{java => authentication}/api/ParameterBuilderTest.java (99%) rename core/src/test/java/com/auth0/{java => authentication}/api/internal/BaseRequestTest.java (94%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/AuthenticationAPI.java (99%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/AuthenticationCallbackMatcher.java (96%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/CallbackMatcher.java (98%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/MockAuthenticationCallback.java (93%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/MockBaseCallback.java (94%) rename core/src/test/java/com/auth0/{java => authentication/api}/util/MockRefreshIdTokenCallback.java (92%) diff --git a/build.gradle b/build.gradle index 42a3cb2f..442acd8d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ allprojects { - group = 'com.auth0.java' - version = '0.1-SNAPSHOT' + group = 'com.auth0' + version = '0.0.1-SNAPSHOT' repositories { mavenCentral() diff --git a/core/src/main/java/com/auth0/java/core/Application.java b/core/src/main/java/com/auth0/Application.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/Application.java rename to core/src/main/java/com/auth0/Application.java index 7ec16ccc..9c7327af 100644 --- a/core/src/main/java/com/auth0/java/core/Application.java +++ b/core/src/main/java/com/auth0/Application.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -31,7 +31,7 @@ import java.util.ArrayList; import java.util.List; -import static com.auth0.java.util.CheckHelper.checkArgument; +import static com.auth0.authentication.api.util.CheckHelper.checkArgument; /** * Class with your Auth0's application information and the list of enabled connections (DB, Social, Enterprise, Passwordless). diff --git a/core/src/main/java/com/auth0/java/core/Auth0.java b/core/src/main/java/com/auth0/Auth0.java similarity index 97% rename from core/src/main/java/com/auth0/java/core/Auth0.java rename to core/src/main/java/com/auth0/Auth0.java index 51087b31..6ab9536e 100644 --- a/core/src/main/java/com/auth0/java/core/Auth0.java +++ b/core/src/main/java/com/auth0/Auth0.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; -import com.auth0.java.api.authentication.AuthenticationAPIClient; +import com.auth0.authentication.AuthenticationAPIClient; import com.squareup.okhttp.HttpUrl; public class Auth0 { diff --git a/core/src/main/java/com/auth0/java/core/Connection.java b/core/src/main/java/com/auth0/Connection.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/Connection.java rename to core/src/main/java/com/auth0/Connection.java index df7c5b9f..4f9b6baf 100644 --- a/core/src/main/java/com/auth0/java/core/Connection.java +++ b/core/src/main/java/com/auth0/Connection.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; -import com.auth0.java.util.CheckHelper; +import com.auth0.authentication.api.util.CheckHelper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/java/core/DatabaseUser.java b/core/src/main/java/com/auth0/DatabaseUser.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/DatabaseUser.java rename to core/src/main/java/com/auth0/DatabaseUser.java index 8738048d..98f7b2b4 100644 --- a/core/src/main/java/com/auth0/java/core/DatabaseUser.java +++ b/core/src/main/java/com/auth0/DatabaseUser.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/core/src/main/java/com/auth0/java/core/Strategies.java b/core/src/main/java/com/auth0/Strategies.java similarity index 93% rename from core/src/main/java/com/auth0/java/core/Strategies.java rename to core/src/main/java/com/auth0/Strategies.java index 408d6f57..aa9aae2d 100644 --- a/core/src/main/java/com/auth0/java/core/Strategies.java +++ b/core/src/main/java/com/auth0/Strategies.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; -import static com.auth0.java.core.Strategies.Type.DATABASE; -import static com.auth0.java.core.Strategies.Type.ENTERPRISE; -import static com.auth0.java.core.Strategies.Type.PASSWORDLESS; -import static com.auth0.java.core.Strategies.Type.SOCIAL; +import static com.auth0.Strategies.Type.DATABASE; +import static com.auth0.Strategies.Type.ENTERPRISE; +import static com.auth0.Strategies.Type.PASSWORDLESS; +import static com.auth0.Strategies.Type.SOCIAL; /** * An enum with all strategies available in Auth0 diff --git a/core/src/main/java/com/auth0/java/core/Strategy.java b/core/src/main/java/com/auth0/Strategy.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/Strategy.java rename to core/src/main/java/com/auth0/Strategy.java index bdfbfb2e..1fb92664 100644 --- a/core/src/main/java/com/auth0/java/core/Strategy.java +++ b/core/src/main/java/com/auth0/Strategy.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/java/core/Token.java b/core/src/main/java/com/auth0/Token.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/Token.java rename to core/src/main/java/com/auth0/Token.java index 91b64e00..4f69d9ea 100644 --- a/core/src/main/java/com/auth0/java/core/Token.java +++ b/core/src/main/java/com/auth0/Token.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/core/src/main/java/com/auth0/java/core/UserIdentity.java b/core/src/main/java/com/auth0/UserIdentity.java similarity index 99% rename from core/src/main/java/com/auth0/java/core/UserIdentity.java rename to core/src/main/java/com/auth0/UserIdentity.java index 58add634..dc6e7094 100644 --- a/core/src/main/java/com/auth0/java/core/UserIdentity.java +++ b/core/src/main/java/com/auth0/UserIdentity.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/java/core/UserProfile.java b/core/src/main/java/com/auth0/UserProfile.java similarity index 98% rename from core/src/main/java/com/auth0/java/core/UserProfile.java rename to core/src/main/java/com/auth0/UserProfile.java index 1ccf3921..807e7953 100644 --- a/core/src/main/java/com/auth0/java/core/UserProfile.java +++ b/core/src/main/java/com/auth0/UserProfile.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; -import com.auth0.java.util.CheckHelper; +import com.auth0.authentication.api.util.CheckHelper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java similarity index 97% rename from core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java rename to core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index a7487f48..fe0b49a9 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -22,24 +22,24 @@ * THE SOFTWARE. */ -package com.auth0.java.api.authentication; - -import com.auth0.java.api.ParameterBuilder; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.Request; -import com.auth0.java.api.internal.RequestFactory; -import com.auth0.java.core.Application; -import com.auth0.java.core.Auth0; -import com.auth0.java.core.DatabaseUser; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; +package com.auth0.authentication; + +import com.auth0.authentication.api.ParameterBuilder; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.Request; +import com.auth0.authentication.api.internal.RequestFactory; +import com.auth0.Application; +import com.auth0.Auth0; +import com.auth0.DatabaseUser; +import com.auth0.Token; +import com.auth0.UserProfile; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; import java.util.Map; -import static com.auth0.java.api.ParameterBuilder.GRANT_TYPE_PASSWORD; +import static com.auth0.authentication.api.ParameterBuilder.GRANT_TYPE_PASSWORD; /** * API client for Auth0 Authentication API. diff --git a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java similarity index 92% rename from core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java rename to core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index 96b5ccde..c76d8484 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -22,14 +22,14 @@ * THE SOFTWARE. */ -package com.auth0.java.api.authentication; +package com.auth0.authentication; -import com.auth0.java.api.ParameterBuilder; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.callback.AuthenticationCallback; -import com.auth0.java.api.callback.BaseCallback; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; +import com.auth0.authentication.api.ParameterBuilder; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.callback.AuthenticationCallback; +import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.Token; +import com.auth0.UserProfile; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java similarity index 92% rename from core/src/main/java/com/auth0/java/api/authentication/DelegationRequest.java rename to core/src/main/java/com/auth0/authentication/DelegationRequest.java index ae12f9a8..7a182451 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -22,11 +22,11 @@ * THE SOFTWARE. */ -package com.auth0.java.api.authentication; +package com.auth0.authentication; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.callback.BaseCallback; -import com.auth0.java.api.callback.RefreshIdTokenCallback; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.authentication.api.callback.RefreshIdTokenCallback; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/authentication/SignUpRequest.java similarity index 93% rename from core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java rename to core/src/main/java/com/auth0/authentication/SignUpRequest.java index 9569b08b..726c8a19 100644 --- a/core/src/main/java/com/auth0/java/api/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.api.authentication; +package com.auth0.authentication; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.callback.AuthenticationCallback; -import com.auth0.java.api.callback.BaseCallback; -import com.auth0.java.core.DatabaseUser; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.callback.AuthenticationCallback; +import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.DatabaseUser; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/APIClientException.java b/core/src/main/java/com/auth0/authentication/api/APIClientException.java similarity index 98% rename from core/src/main/java/com/auth0/java/api/APIClientException.java rename to core/src/main/java/com/auth0/authentication/api/APIClientException.java index 81e5d4e1..20c51249 100644 --- a/core/src/main/java/com/auth0/java/api/APIClientException.java +++ b/core/src/main/java/com/auth0/authentication/api/APIClientException.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java b/core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java similarity index 97% rename from core/src/main/java/com/auth0/java/api/AuthorizableRequest.java rename to core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java index b2700724..e6695525 100644 --- a/core/src/main/java/com/auth0/java/api/AuthorizableRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; /** * Interface for a Auth0 request that need Authorization using a JWT diff --git a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java b/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java similarity index 98% rename from core/src/main/java/com/auth0/java/api/ParameterBuilder.java rename to core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java index 50b924c0..6b7a10f6 100644 --- a/core/src/main/java/com/auth0/java/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; -import com.auth0.java.util.CheckHelper; +import com.auth0.authentication.api.util.CheckHelper; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java b/core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java similarity index 97% rename from core/src/main/java/com/auth0/java/api/ParameterizableRequest.java rename to core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java index 80ac1b47..e014675a 100644 --- a/core/src/main/java/com/auth0/java/api/ParameterizableRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; import java.util.Map; diff --git a/core/src/main/java/com/auth0/java/api/Request.java b/core/src/main/java/com/auth0/authentication/api/Request.java similarity index 93% rename from core/src/main/java/com/auth0/java/api/Request.java rename to core/src/main/java/com/auth0/authentication/api/Request.java index 5b591afc..19c27bf2 100644 --- a/core/src/main/java/com/auth0/java/api/Request.java +++ b/core/src/main/java/com/auth0/authentication/api/Request.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; -import com.auth0.java.api.callback.BaseCallback; +import com.auth0.authentication.api.callback.BaseCallback; /** * Defines a request that can be started diff --git a/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java similarity index 97% rename from core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java rename to core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java index 4cd1c2f8..2f31e81a 100644 --- a/core/src/main/java/com/auth0/java/api/RequestBodyBuildException.java +++ b/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; /** * Exception that wraps errors when creating a body for a request diff --git a/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java b/core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java similarity index 93% rename from core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java rename to core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java index b508a964..8b50af8a 100644 --- a/core/src/main/java/com/auth0/java/api/callback/AuthenticationCallback.java +++ b/core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.java.api.callback; +package com.auth0.authentication.api.callback; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; +import com.auth0.Token; +import com.auth0.UserProfile; /** * Callback for authentication API calls to Auth0 API. diff --git a/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java b/core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java similarity index 96% rename from core/src/main/java/com/auth0/java/api/callback/BaseCallback.java rename to core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java index 34563662..9b109b33 100644 --- a/core/src/main/java/com/auth0/java/api/callback/BaseCallback.java +++ b/core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api.callback; +package com.auth0.authentication.api.callback; /** * Callback that receives a single value on success. diff --git a/core/src/main/java/com/auth0/java/api/callback/Callback.java b/core/src/main/java/com/auth0/authentication/api/callback/Callback.java similarity index 96% rename from core/src/main/java/com/auth0/java/api/callback/Callback.java rename to core/src/main/java/com/auth0/authentication/api/callback/Callback.java index 35df298e..8b746f05 100644 --- a/core/src/main/java/com/auth0/java/api/callback/Callback.java +++ b/core/src/main/java/com/auth0/authentication/api/callback/Callback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api.callback; +package com.auth0.authentication.api.callback; /** * Interface for all callbacks used with Auth0 API clients diff --git a/core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java b/core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java similarity index 97% rename from core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java rename to core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java index 1187f5ee..337661bc 100644 --- a/core/src/main/java/com/auth0/java/api/callback/RefreshIdTokenCallback.java +++ b/core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api.callback; +package com.auth0.authentication.api.callback; /** * Callback used in delegation api request for a new Auth0 id_token diff --git a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java similarity index 95% rename from core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java rename to core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index 81839de8..ec8ca3b4 100644 --- a/core/src/main/java/com/auth0/java/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -22,11 +22,11 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.APIClientException; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.core.Application; +import com.auth0.authentication.api.APIClientException; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.Application; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; diff --git a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java similarity index 93% rename from core/src/main/java/com/auth0/java/api/internal/BaseRequest.java rename to core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java index 1d71266f..136dec1c 100644 --- a/core/src/main/java/com/auth0/java/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java @@ -22,13 +22,13 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.APIClientException; -import com.auth0.java.api.AuthorizableRequest; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.RequestBodyBuildException; -import com.auth0.java.api.callback.BaseCallback; +import com.auth0.authentication.api.APIClientException; +import com.auth0.authentication.api.AuthorizableRequest; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.RequestBodyBuildException; +import com.auth0.authentication.api.callback.BaseCallback; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; diff --git a/core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java b/core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java similarity index 94% rename from core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java rename to core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java index a131c126..931ab977 100644 --- a/core/src/main/java/com/auth0/java/api/internal/JsonRequestBodyBuilder.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.RequestBodyBuildException; +import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.MediaType; diff --git a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java similarity index 94% rename from core/src/main/java/com/auth0/java/api/internal/RequestFactory.java rename to core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java index 76f9ea04..6c0d8457 100644 --- a/core/src/main/java/com/auth0/java/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.AuthorizableRequest; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.Request; -import com.auth0.java.core.Application; +import com.auth0.authentication.api.AuthorizableRequest; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.Request; +import com.auth0.Application; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; diff --git a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java similarity index 93% rename from core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java rename to core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java index 6e4da124..783d1c3f 100644 --- a/core/src/main/java/com/auth0/java/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.APIClientException; -import com.auth0.java.api.ParameterizableRequest; -import com.auth0.java.api.Request; -import com.auth0.java.api.RequestBodyBuildException; +import com.auth0.authentication.api.APIClientException; +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.Request; +import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; diff --git a/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java similarity index 96% rename from core/src/main/java/com/auth0/java/api/internal/VoidRequest.java rename to core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java index 249bb068..2f0b2367 100644 --- a/core/src/main/java/com/auth0/java/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.APIClientException; +import com.auth0.authentication.api.APIClientException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; diff --git a/core/src/main/java/com/auth0/java/util/CheckHelper.java b/core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java similarity index 97% rename from core/src/main/java/com/auth0/java/util/CheckHelper.java rename to core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java index e6e14941..879b1be0 100644 --- a/core/src/main/java/com/auth0/java/util/CheckHelper.java +++ b/core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; /** * A helper to check constructor arguments. diff --git a/core/src/test/java/com/auth0/java/core/ApplicationTest.java b/core/src/test/java/com/auth0/ApplicationTest.java similarity index 91% rename from core/src/test/java/com/auth0/java/core/ApplicationTest.java rename to core/src/test/java/com/auth0/ApplicationTest.java index f8bda589..07dbe99e 100644 --- a/core/src/test/java/com/auth0/java/core/ApplicationTest.java +++ b/core/src/test/java/com/auth0/ApplicationTest.java @@ -22,7 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; + +import com.auth0.Application; +import com.auth0.Connection; +import com.auth0.Strategies; +import com.auth0.Strategy; import org.junit.Test; @@ -30,12 +35,12 @@ import java.util.Arrays; import java.util.List; -import static com.auth0.java.core.Strategies.ADFS; -import static com.auth0.java.core.Strategies.Auth0; -import static com.auth0.java.core.Strategies.Facebook; -import static com.auth0.java.core.Strategies.Office365; -import static com.auth0.java.core.Strategies.SAMLP; -import static com.auth0.java.core.Strategies.Twitter; +import static com.auth0.Strategies.ADFS; +import static com.auth0.Strategies.Auth0; +import static com.auth0.Strategies.Facebook; +import static com.auth0.Strategies.Office365; +import static com.auth0.Strategies.SAMLP; +import static com.auth0.Strategies.Twitter; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; diff --git a/core/src/test/java/com/auth0/java/core/Auth0Test.java b/core/src/test/java/com/auth0/Auth0Test.java similarity index 98% rename from core/src/test/java/com/auth0/java/core/Auth0Test.java rename to core/src/test/java/com/auth0/Auth0Test.java index 3a78830e..8a732815 100644 --- a/core/src/test/java/com/auth0/java/core/Auth0Test.java +++ b/core/src/test/java/com/auth0/Auth0Test.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; -import com.auth0.java.api.authentication.AuthenticationAPIClient; +import com.auth0.authentication.AuthenticationAPIClient; import org.junit.Test; diff --git a/core/src/test/java/com/auth0/java/core/ConnectionTest.java b/core/src/test/java/com/auth0/ConnectionTest.java similarity index 99% rename from core/src/test/java/com/auth0/java/core/ConnectionTest.java rename to core/src/test/java/com/auth0/ConnectionTest.java index b8d11dfd..21c7b129 100644 --- a/core/src/test/java/com/auth0/java/core/ConnectionTest.java +++ b/core/src/test/java/com/auth0/ConnectionTest.java @@ -22,7 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; + +import com.auth0.Connection; import org.junit.Rule; import org.junit.Test; diff --git a/core/src/test/java/com/auth0/java/core/StrategiesTest.java b/core/src/test/java/com/auth0/StrategiesTest.java similarity index 97% rename from core/src/test/java/com/auth0/java/core/StrategiesTest.java rename to core/src/test/java/com/auth0/StrategiesTest.java index 555d8d1b..82d6da5b 100644 --- a/core/src/test/java/com/auth0/java/core/StrategiesTest.java +++ b/core/src/test/java/com/auth0/StrategiesTest.java @@ -22,7 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; + +import com.auth0.Strategies; import org.junit.Test; diff --git a/core/src/test/java/com/auth0/java/core/UserProfileTest.java b/core/src/test/java/com/auth0/UserProfileTest.java similarity index 98% rename from core/src/test/java/com/auth0/java/core/UserProfileTest.java rename to core/src/test/java/com/auth0/UserProfileTest.java index f4dd7203..9c1f2b50 100644 --- a/core/src/test/java/com/auth0/java/core/UserProfileTest.java +++ b/core/src/test/java/com/auth0/UserProfileTest.java @@ -22,9 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.java.core; +package com.auth0; +import com.auth0.UserIdentity; +import com.auth0.UserProfile; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; diff --git a/core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java similarity index 94% rename from core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java rename to core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index dc871cde..9814e956 100644 --- a/core/src/test/java/com/auth0/java/api/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -22,19 +22,19 @@ * THE SOFTWARE. */ -package com.auth0.java.api.authentication; - - -import com.auth0.java.api.ParameterBuilder; -import com.auth0.java.core.Application; -import com.auth0.java.core.Auth0; -import com.auth0.java.core.DatabaseUser; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; -import com.auth0.java.util.AuthenticationAPI; -import com.auth0.java.util.MockAuthenticationCallback; -import com.auth0.java.util.MockBaseCallback; -import com.auth0.java.util.MockRefreshIdTokenCallback; +package com.auth0.authentication; + + +import com.auth0.authentication.api.ParameterBuilder; +import com.auth0.Application; +import com.auth0.Auth0; +import com.auth0.DatabaseUser; +import com.auth0.Token; +import com.auth0.UserProfile; +import com.auth0.authentication.api.util.AuthenticationAPI; +import com.auth0.authentication.api.util.MockAuthenticationCallback; +import com.auth0.authentication.api.util.MockBaseCallback; +import com.auth0.authentication.api.util.MockRefreshIdTokenCallback; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.mockwebserver.RecordedRequest; @@ -42,21 +42,19 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.HashMap; import java.util.Map; -import static com.auth0.java.util.AuthenticationAPI.GENERIC_TOKEN; -import static com.auth0.java.util.AuthenticationAPI.ID_TOKEN; -import static com.auth0.java.util.AuthenticationAPI.NEW_ID_TOKEN; -import static com.auth0.java.util.AuthenticationAPI.REFRESH_TOKEN; -import static com.auth0.java.util.AuthenticationCallbackMatcher.hasTokenAndProfile; -import static com.auth0.java.util.CallbackMatcher.hasNoError; -import static com.auth0.java.util.CallbackMatcher.hasNoPayloadOfType; -import static com.auth0.java.util.CallbackMatcher.hasPayload; -import static com.auth0.java.util.CallbackMatcher.hasPayloadOfType; +import static com.auth0.authentication.api.util.AuthenticationAPI.GENERIC_TOKEN; +import static com.auth0.authentication.api.util.AuthenticationAPI.ID_TOKEN; +import static com.auth0.authentication.api.util.AuthenticationAPI.NEW_ID_TOKEN; +import static com.auth0.authentication.api.util.AuthenticationAPI.REFRESH_TOKEN; +import static com.auth0.authentication.api.util.AuthenticationCallbackMatcher.hasTokenAndProfile; +import static com.auth0.authentication.api.util.CallbackMatcher.hasNoError; +import static com.auth0.authentication.api.util.CallbackMatcher.hasNoPayloadOfType; +import static com.auth0.authentication.api.util.CallbackMatcher.hasPayload; +import static com.auth0.authentication.api.util.CallbackMatcher.hasPayloadOfType; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; @@ -64,7 +62,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; public class AuthenticationAPIClientTest { diff --git a/core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java b/core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java similarity index 99% rename from core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java rename to core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java index 24dbfced..be6902ab 100644 --- a/core/src/test/java/com/auth0/java/api/ParameterBuilderTest.java +++ b/core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.api; +package com.auth0.authentication.api; import org.hamcrest.Matcher; diff --git a/core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java similarity index 94% rename from core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java rename to core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java index 944c9472..421b4d2a 100644 --- a/core/src/test/java/com/auth0/java/api/internal/BaseRequestTest.java +++ b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java @@ -22,11 +22,11 @@ * THE SOFTWARE. */ -package com.auth0.java.api.internal; +package com.auth0.authentication.api.internal; -import com.auth0.java.api.RequestBodyBuildException; -import com.auth0.java.api.callback.BaseCallback; +import com.auth0.authentication.api.RequestBodyBuildException; +import com.auth0.authentication.api.callback.BaseCallback; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.HttpUrl; diff --git a/core/src/test/java/com/auth0/java/util/AuthenticationAPI.java b/core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java similarity index 99% rename from core/src/test/java/com/auth0/java/util/AuthenticationAPI.java rename to core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java index b7be51d5..bebff34b 100644 --- a/core/src/test/java/com/auth0/java/util/AuthenticationAPI.java +++ b/core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; diff --git a/core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java b/core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java similarity index 96% rename from core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java rename to core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java index 9db17864..bc4875f4 100644 --- a/core/src/test/java/com/auth0/java/util/AuthenticationCallbackMatcher.java +++ b/core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; +import com.auth0.Token; +import com.auth0.UserProfile; import com.jayway.awaitility.core.ConditionTimeoutException; import org.hamcrest.BaseMatcher; diff --git a/core/src/test/java/com/auth0/java/util/CallbackMatcher.java b/core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java similarity index 98% rename from core/src/test/java/com/auth0/java/util/CallbackMatcher.java rename to core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java index 10ea662c..dcfc151e 100644 --- a/core/src/test/java/com/auth0/java/util/CallbackMatcher.java +++ b/core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; import com.jayway.awaitility.core.ConditionTimeoutException; diff --git a/core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java similarity index 93% rename from core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java rename to core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java index 3178ec75..d90d65c7 100644 --- a/core/src/test/java/com/auth0/java/util/MockAuthenticationCallback.java +++ b/core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java @@ -22,11 +22,11 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; -import com.auth0.java.api.callback.AuthenticationCallback; -import com.auth0.java.core.Token; -import com.auth0.java.core.UserProfile; +import com.auth0.authentication.api.callback.AuthenticationCallback; +import com.auth0.Token; +import com.auth0.UserProfile; import java.util.concurrent.Callable; diff --git a/core/src/test/java/com/auth0/java/util/MockBaseCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java similarity index 94% rename from core/src/test/java/com/auth0/java/util/MockBaseCallback.java rename to core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java index 03d0f0ba..7cebc16e 100644 --- a/core/src/test/java/com/auth0/java/util/MockBaseCallback.java +++ b/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; -import com.auth0.java.api.callback.BaseCallback; +import com.auth0.authentication.api.callback.BaseCallback; import java.util.concurrent.Callable; diff --git a/core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java similarity index 92% rename from core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java rename to core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java index dd2b7bc9..2a8a7233 100644 --- a/core/src/test/java/com/auth0/java/util/MockRefreshIdTokenCallback.java +++ b/core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.java.util; +package com.auth0.authentication.api.util; -import com.auth0.java.api.callback.RefreshIdTokenCallback; +import com.auth0.authentication.api.callback.RefreshIdTokenCallback; public class MockRefreshIdTokenCallback extends MockBaseCallback implements RefreshIdTokenCallback { From 98a2ba3b574cab676a7dfd1d167fdb451f48df74 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 15:16:30 -0300 Subject: [PATCH 16/89] Remove everything Log related (TAG string and Log calls) --- .../com/auth0/authentication/AuthenticationAPIClient.java | 7 ------- .../api/internal/ApplicationInfoRequest.java | 4 ---- .../com/auth0/authentication/api/internal/BaseRequest.java | 4 ---- .../auth0/authentication/api/internal/SimpleRequest.java | 4 ---- .../com/auth0/authentication/api/internal/VoidRequest.java | 3 --- 5 files changed, 22 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index fe0b49a9..b28b750c 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -47,8 +47,6 @@ */ public class AuthenticationAPIClient { - private static final String TAG = AuthenticationAPIClient.class.getName(); - private static final String USERNAME_KEY = "username"; private static final String PASSWORD_KEY = "password"; private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; @@ -134,7 +132,6 @@ public ParameterizableRequest loginWithResourceOwner() { .asDictionary(); ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) .addParameters(requestParameters); - //Log.d(TAG, "Trying to login using " + url.toString() + " with parameters " + requestParameters); return request; } @@ -171,8 +168,6 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .setAccessToken(token) .asDictionary(); - //Log.v(TAG, "Performing OAuth access_token login with parameters " + parameters); - final ParameterizableRequest profileRequest = profileRequest(); ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, mapper, Token.class) .addParameters(parameters); @@ -223,7 +218,6 @@ public Request tokenInfo(String idToken) { .clearAll() .set(ID_TOKEN_KEY, idToken) .asDictionary(); - //Log.d(TAG, "Trying to fetch token with parameters " + requestParameters); return profileRequest() .addParameters(requestParameters); } @@ -247,7 +241,6 @@ public ParameterizableRequest createUser(String email, String pass .setConnection(defaultDbConnection) .setClientId(getClientId()) .asDictionary(); - //Log.d(TAG, "Creating user with email " + email + " and username " + username); return RequestFactory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index ec8ca3b4..2d116ad2 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -43,8 +43,6 @@ class ApplicationInfoRequest extends BaseRequest implements Callback { - private static final String TAG = ApplicationInfoRequest.class.getName(); - public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper mapper) { super(url, client, mapper.reader(Application.class), null); } @@ -52,7 +50,6 @@ public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper map @Override protected Request doBuildRequest(Request.Builder builder) { final Request request = builder.build(); - //Log.v(TAG, "Fetching application info from " + request.urlString()); return request; } @@ -86,7 +83,6 @@ public void onResponse(Response response) throws IOException { postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info")); } JSONObject jsonObject = (JSONObject) nextValue; - //Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject); Application app = getReader().readValue(jsonObject.toString()); postOnSuccess(app); diff --git a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java index 136dec1c..3379a907 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java @@ -43,8 +43,6 @@ abstract class BaseRequest implements ParameterizableRequest, AuthorizableRequest, Callback { - private static final String TAG = BaseCallback.class.getName(); - private final Map headers; private final Map parameters; protected final HttpUrl url; @@ -77,7 +75,6 @@ protected void postOnSuccess(final T payload) { } protected final void postOnFailure(final Throwable error) { - //Log.e(TAG, "Failed to make request to " + url, error); this.callback.onFailure(error); } @@ -142,7 +139,6 @@ public void start(BaseCallback callback) { Request request = doBuildRequest(newBuilder()); client.newCall(request).enqueue(this); } catch (RequestBodyBuildException e) { - //Log.e(TAG, "Failed to build JSON body with parameters " + parameters, e); callback.onFailure(new APIClientException("Failed to send request to " + url.toString(), e)); } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java index 783d1c3f..30d56d61 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java @@ -43,8 +43,6 @@ class SimpleRequest extends BaseRequest implements Request, ParameterizableRequest, Callback { - private static final String TAG = SimpleRequest.class.getName(); - private final ObjectReader errorReader; private final String method; @@ -63,7 +61,6 @@ public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Stri @Override public void onResponse(Response response) throws IOException { - //Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable; @@ -78,7 +75,6 @@ public void onResponse(Response response) throws IOException { } try { - //Log.d(TAG, "Received successful response from " + response.request().urlString()); T payload = getReader().readValue(byteStream); postOnSuccess(payload); } catch (IOException e) { diff --git a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java index 2f0b2367..73be39e6 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java @@ -40,8 +40,6 @@ class VoidRequest extends BaseRequest implements Callback { - private static final String TAG = VoidRequest.class.getName(); - private final ObjectReader errorReader; private final String httpMethod; @@ -54,7 +52,6 @@ public VoidRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String @Override public void onResponse(Response response) throws IOException { - //Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable; From e03c0f9c49d9de07baf8669518b33eb51e1426fd Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 16:32:35 -0300 Subject: [PATCH 17/89] Add methods to set scope, target and api type to the delegation request --- .../AuthenticationAPIClient.java | 5 +-- .../authentication/DelegationRequest.java | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index b28b750c..23d43a3c 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -53,8 +53,7 @@ public class AuthenticationAPIClient { private static final String ID_TOKEN_KEY = "id_token"; private static final String EMAIL_KEY = "email"; private static final String REFRESH_TOKEN_KEY = "refresh_token"; - private static final String API_TYPE_KEY = "api_type"; - private static final String DEFAULT_API_TYPE = "app"; + private static final String PHONE_NUMBER_KEY = "phone_number"; private final Auth0 auth0; @@ -331,7 +330,6 @@ public DelegationRequest delegationWithIdToken(String idToken) { Map parameters = new ParameterBuilder() .clearAll() .set(ID_TOKEN_KEY, idToken) - .set(API_TYPE_KEY, DEFAULT_API_TYPE) .asDictionary(); ParameterizableRequest> request = delegation() .addParameters(parameters); @@ -348,7 +346,6 @@ public DelegationRequest delegationWithRefreshToken(String refreshToken) { Map parameters = new ParameterBuilder() .clearAll() .set(REFRESH_TOKEN_KEY, refreshToken) - .set(API_TYPE_KEY, DEFAULT_API_TYPE) .asDictionary(); ParameterizableRequest> request = delegation() .addParameters(parameters); diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index 7a182451..93768773 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -24,10 +24,12 @@ package com.auth0.authentication; +import com.auth0.authentication.api.ParameterBuilder; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.callback.BaseCallback; import com.auth0.authentication.api.callback.RefreshIdTokenCallback; +import java.util.HashMap; import java.util.Map; /** @@ -39,10 +41,23 @@ public class DelegationRequest { private static final String EXPIRES_IN_KEY = "expires_in"; private static final String ID_TOKEN_KEY = "id_token"; + private static final String API_TYPE_KEY = "api_type"; + private static final String DEFAULT_API_TYPE = "app"; + + private static final String TARGET_KEY = "target"; + private final ParameterizableRequest> request; DelegationRequest(ParameterizableRequest> request) { this.request = request; + addParameter(API_TYPE_KEY, DEFAULT_API_TYPE); + } + + private DelegationRequest addParameter(String key, Object value) { + Map parameters = new HashMap<>(); + parameters.put(key, value); + request.addParameters(parameters); + return this; } /** @@ -55,6 +70,33 @@ public DelegationRequest addParameters(Map parameters) { return this; } + /** + * Set the api_type parameter to be sent in the request + * @param apiType the delegation api type + * @return itself + */ + public DelegationRequest setApiType(String apiType) { + return addParameter(TARGET_KEY, apiType); + } + + /** + * Set the scope used to make the delegation + * @param scope value + * @return itself + */ + public DelegationRequest setScope(String scope) { + return addParameters(new ParameterBuilder().clearAll().setScope(scope).asDictionary()); + } + + /** + * Set the target parameter to be sent in the request + * @param target the delegation target + * @return itself + */ + public DelegationRequest setTarget(String target) { + return addParameter(TARGET_KEY, target); + } + /** * Performs the HTTP request against Auth0 API * @param callback called either on success or failure From 6b4f9c93e37d34ce86c7205e4f5681b59c7087a1 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 16:55:04 -0300 Subject: [PATCH 18/89] Add PasswordlessType enum and use it when starting a passwordless flow --- .../AuthenticationAPIClient.java | 14 +-- .../authentication/PasswordlessType.java | 35 ++++++++ .../authentication/api/ParameterBuilder.java | 21 +++++ .../AuthenticationAPIClientTest.java | 88 ++++++++++++++++++- 4 files changed, 147 insertions(+), 11 deletions(-) create mode 100644 core/src/main/java/com/auth0/authentication/PasswordlessType.java diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 23d43a3c..e712b4e5 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -394,14 +394,14 @@ public ParameterizableRequest passwordless() { /** * Start a passwordless flow with either Email * @param email that will receive a verification code to use for login - * @param useMagicLink whether the email should contain the magic link or the code + * @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS) * @return a request to configure and start */ - public ParameterizableRequest passwordlessWithEmail(String email, boolean useMagicLink) { + public ParameterizableRequest passwordlessWithEmail(String email, PasswordlessType passwordlessType) { Map parameters = ParameterBuilder.newBuilder() .clearAll() .set(EMAIL_KEY, email) - .set("send", useMagicLink ? "link_android" : "code") + .setSend(passwordlessType) .setConnection("email") .asDictionary(); return passwordless() @@ -411,14 +411,14 @@ public ParameterizableRequest passwordlessWithEmail(String email, boolean /** * Start a passwordless flow with SMS * @param phoneNumber where an SMS with a verification code will be sent - * @param useMagicLink whether the SMS should contain the magic link or the code - * @return a request to configure and stat + * @param passwordlessType indicate whether the SMS should contain a code, link or magic link (android & iOS) + * @return a request to configure and start */ - public ParameterizableRequest passwordlessWithSMS(String phoneNumber, boolean useMagicLink) { + public ParameterizableRequest passwordlessWithSMS(String phoneNumber, PasswordlessType passwordlessType) { Map parameters = ParameterBuilder.newBuilder() .clearAll() .set(PHONE_NUMBER_KEY, phoneNumber) - .set("send", useMagicLink ? "link_android" : "code") + .setSend(passwordlessType) .setConnection("sms") .asDictionary(); return passwordless() diff --git a/core/src/main/java/com/auth0/authentication/PasswordlessType.java b/core/src/main/java/com/auth0/authentication/PasswordlessType.java new file mode 100644 index 00000000..124d071b --- /dev/null +++ b/core/src/main/java/com/auth0/authentication/PasswordlessType.java @@ -0,0 +1,35 @@ +/* + * PasswordlessType.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.authentication; + +/** + * An enum with all passwordless login types available in Auth0 + */ +public enum PasswordlessType { + LINK, + LINK_ANDROID, + LINK_IOS, + CODE +} diff --git a/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java b/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java index 6b7a10f6..c69f088d 100644 --- a/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java @@ -24,6 +24,7 @@ package com.auth0.authentication.api; +import com.auth0.authentication.PasswordlessType; import com.auth0.authentication.api.util.CheckHelper; import java.util.HashMap; @@ -38,6 +39,7 @@ public class ParameterBuilder { public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; public static final String ACCESS_TOKEN = "access_token"; public static final String CONNECTION = "connection"; + public static final String SEND = "send"; public static final String GRANT_TYPE_PASSWORD = "password"; public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; @@ -115,6 +117,25 @@ public ParameterBuilder setAccessToken(String accessToken) { return set(ACCESS_TOKEN, accessToken); } + /** + * Sets the 'send' parameter + * @param passwordlessType the type of passwordless login + * @return itself + */ + public ParameterBuilder setSend(PasswordlessType passwordlessType) { + switch (passwordlessType) { + default: + case CODE: + return set(SEND, "code"); + case LINK: + return set(SEND, "link"); + case LINK_ANDROID: + return set(SEND, "link_android"); + case LINK_IOS: + return set(SEND, "link_ios"); + } + } + /** * Sets a parameter * @param key parameter name diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 9814e956..e2a397a1 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -486,7 +486,7 @@ public void shouldSendEmailCode() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", false) + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.CODE) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -506,7 +506,27 @@ public void shouldSendEmailLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", true) + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendEmailLinkAndroid() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_ANDROID) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -521,12 +541,32 @@ public void shouldSendEmailLink() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendEmailLinkIOS() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_IOS) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link_ios")); + assertThat(body, hasEntry("connection", "email")); + + assertThat(callback, hasNoError()); + } + @Test public void shouldSendSMSCode() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithSMS("+1123123123", false) + client.passwordlessWithSMS("+1123123123", PasswordlessType.CODE) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -546,7 +586,27 @@ public void shouldSendSMSLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithSMS("+1123123123", true) + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + + @Test + public void shouldSendSMSLinkAndroid() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_ANDROID) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -561,6 +621,26 @@ public void shouldSendSMSLink() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendSMSLinkIOS() throws Exception { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_IOS) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link_ios")); + assertThat(body, hasEntry("connection", "sms")); + + assertThat(callback, hasNoError()); + } + private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); } From 7f790602a1c0533ee05832c243f47150b506aa77 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 17:39:31 -0300 Subject: [PATCH 19/89] Add test for DelegationRequest customization. Fix typo --- .../authentication/DelegationRequest.java | 2 +- .../AuthenticationAPIClientTest.java | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index 93768773..ef0f37ce 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -76,7 +76,7 @@ public DelegationRequest addParameters(Map parameters) { * @return itself */ public DelegationRequest setApiType(String apiType) { - return addParameter(TARGET_KEY, apiType); + return addParameter(API_TYPE_KEY, apiType); } /** diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index e2a397a1..4c3db959 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -435,6 +435,31 @@ public void shouldGetNewIdTokenWithRefreshToken() throws Exception { assertThat(callback, hasPayload(NEW_ID_TOKEN)); } + @Test + public void shouldGetCustomizedDelegationRequest() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + client.delegationWithRefreshToken(REFRESH_TOKEN) + .setApiType("custom_api_type") + .setScope("custom_scope") + .setTarget("custom_target") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "custom_api_type")); + assertThat(body, hasEntry("scope", "custom_scope")); + assertThat(body, hasEntry("target", "custom_target")); + assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); + + assertThat(callback, hasPayload(NEW_ID_TOKEN)); + } + @Test public void shouldUnlinkAccount() throws Exception { mockAPI.willReturnSuccessfulUnlinkAccount(); From 49ad09ad4382de6a233b7cb200864d49ea92ee6e Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 18:20:06 -0300 Subject: [PATCH 20/89] Refactor changePassword to allow more flexible usage The new password can optionally be added to the request using the setNewPassword method, but is not mandatory The change_password endpoint allows to initiate a change password request without setting a new password See https://auth0.com/docs/auth-api#!#post--dbconnections-change_password --- .../AuthenticationAPIClient.java | 7 +- .../authentication/ChangePasswordRequest.java | 92 +++++++++++++++++++ .../AuthenticationAPIClientTest.java | 27 +++++- 3 files changed, 118 insertions(+), 8 deletions(-) create mode 100644 core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index e712b4e5..452c751a 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -284,10 +284,9 @@ public SignUpRequest signUp(String email, String password) { /** * Perform a change password request using '/dbconnections/change_password' * @param email of the user that changes the password. It's also where the confirmation email will be sent - * @param newPassword to use * @return a request to configure and start */ - public ParameterizableRequest changePassword(String email, String newPassword) { + public ChangePasswordRequest changePassword(String email) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("dbconnections") .addPathSegment("change_password") @@ -295,13 +294,13 @@ public ParameterizableRequest changePassword(String email, String newPassw Map parameters = ParameterBuilder.newBuilder() .set(EMAIL_KEY, email) - .set(PASSWORD_KEY, newPassword) .setClientId(getClientId()) .setConnection(defaultDbConnection) .asDictionary(); - return RequestFactory.POST(url, client, mapper) + ParameterizableRequest request = RequestFactory.POST(url, client, mapper) .addParameters(parameters); + return new ChangePasswordRequest(request); } /** diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java new file mode 100644 index 00000000..0e7d01bf --- /dev/null +++ b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -0,0 +1,92 @@ +/* + * ChangePasswordRequest.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.authentication; + +import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.callback.BaseCallback; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represent a request to change a user's password. + */ +public class ChangePasswordRequest implements ParameterizableRequest { + + private static final String PASSWORD_KEY = "password"; + + private final ParameterizableRequest request; + + ChangePasswordRequest(ParameterizableRequest request) { + this.request = request; + } + + private ChangePasswordRequest addParameter(String key, Object value) { + Map parameters = new HashMap<>(); + parameters.put(key, value); + return addParameters(parameters); + } + + /** + * Set the 'password' parameter to be sent in the request + * @param newPassword the new password + * @return itself + */ + public ChangePasswordRequest setNewPassword(String newPassword) { + return addParameter(PASSWORD_KEY, newPassword); + } + + /** + * Adds additional parameters to be sent in the request + * @param parameters as a non-null dictionary + * @return itself + */ + @Override + public ChangePasswordRequest addParameters(Map parameters) { + request.addParameters(parameters); + return this; + } + + /** + * Adds an additional header for the request + * @param name of the header + * @param value of the header + * @return itself + */ + @Override + public ChangePasswordRequest addHeader(String name, String value) { + request.addHeader(name, value); + return this; + } + + /** + * Performs the HTTP request against Auth0 API + * @param callback called either on success or failure + */ + @Override + public void start(final BaseCallback callback) { + request.start(callback); + } +} diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 4c3db959..9eb4e653 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -57,11 +57,11 @@ import static com.auth0.authentication.api.util.CallbackMatcher.hasPayloadOfType; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; public class AuthenticationAPIClientTest { @@ -311,7 +311,6 @@ public void shouldCreateUserWithoutUsername() throws Exception { assertThat(body, hasEntry("password", "123123123")); assertThat(callback, hasPayloadOfType(DatabaseUser.class)); - } @Test @@ -361,7 +360,8 @@ public void shouldChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.changePassword("support@auth0.com", "123123123") + client.changePassword("support@auth0.com") + .setNewPassword("123123123") .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -369,12 +369,31 @@ public void shouldChangePassword() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); + assertThat(body, not(hasKey("username"))); assertThat(body, hasEntry("password", "123123123")); assertThat(callback, hasNoError()); } + @Test + public void shouldRequestChangePassword() throws Exception { + mockAPI.willReturnSuccessfulChangePassword(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.changePassword("support@auth0.com") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasKey("username"))); + assertThat(body, not(hasKey("password"))); + + assertThat(callback, hasNoError()); + } + @Test public void shouldCallDelegation() throws Exception { mockAPI.willReturnGenericDelegationToken(); From 1b101e4c6a0a6626b2010f85233b7a959369b532 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 18:43:46 -0300 Subject: [PATCH 21/89] Make methods protected --- .../AuthenticationAPIClient.java | 101 ++++++++---------- 1 file changed, 44 insertions(+), 57 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 452c751a..18affb04 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -115,25 +115,6 @@ public Request fetchApplicationInfo() { return RequestFactory.newApplicationInfoRequest(url, client, mapper); } - /** - * Log in a user using resource owner endpoint ('/oauth/ro') - * @return a request to configure and start - */ - public ParameterizableRequest loginWithResourceOwner() { - HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("oauth") - .addPathSegment("ro") - .build(); - - Map requestParameters = new ParameterBuilder() - .setClientId(getClientId()) - .setConnection(defaultDbConnection) - .asDictionary(); - ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) - .addParameters(requestParameters); - return request; - } - /** * Log in a user with email/username and password using a DB connection and fetch it's profile from Auth0 * @param usernameOrEmail of the user depending of the type of DB connection @@ -303,23 +284,6 @@ public ChangePasswordRequest changePassword(String email) { return new ChangePasswordRequest(request); } - /** - * Performs a delegation request - * @return a request to configure and start - */ - public ParameterizableRequest> delegation() { - HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("delegation") - .build(); - Map parameters = ParameterBuilder.newEmptyBuilder() - .clearAll() - .setClientId(getClientId()) - .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) - .asDictionary(); - return RequestFactory.rawPOST(url, client, mapper) - .addParameters(parameters); - } - /** * Performs a delegation request that will yield a new Auth0 'id_token' * @param idToken issued by Auth0 for the user. The token must not be expired. @@ -372,26 +336,7 @@ public Request unlink(String userId, String accessToken) { } /** - * Start a passwordless flow with either Email or SMS - * @return a request to configure and stat - */ - public ParameterizableRequest passwordless() { - HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("passwordless") - .addPathSegment("start") - .build(); - - Map parameters = ParameterBuilder.newBuilder() - .clearAll() - .setClientId(getClientId()) - .asDictionary(); - - return RequestFactory.POST(url, client, mapper) - .addParameters(parameters); - } - - /** - * Start a passwordless flow with either Email + * Start a passwordless flow with Email * @param email that will receive a verification code to use for login * @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS) * @return a request to configure and start @@ -424,6 +369,49 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass .addParameters(parameters); } + protected ParameterizableRequest> delegation() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("delegation") + .build(); + Map parameters = ParameterBuilder.newEmptyBuilder() + .clearAll() + .setClientId(getClientId()) + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) + .asDictionary(); + return RequestFactory.rawPOST(url, client, mapper) + .addParameters(parameters); + } + + protected ParameterizableRequest passwordless() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("passwordless") + .addPathSegment("start") + .build(); + + Map parameters = ParameterBuilder.newBuilder() + .clearAll() + .setClientId(getClientId()) + .asDictionary(); + + return RequestFactory.POST(url, client, mapper) + .addParameters(parameters); + } + + protected ParameterizableRequest loginWithResourceOwner() { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("oauth") + .addPathSegment("ro") + .build(); + + Map requestParameters = new ParameterBuilder() + .setClientId(getClientId()) + .setConnection(defaultDbConnection) + .asDictionary(); + ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) + .addParameters(requestParameters); + return request; + } + private ParameterizableRequest profileRequest() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("tokeninfo") @@ -439,5 +427,4 @@ private AuthenticationRequest newAuthenticationRequest(Map param return new AuthenticationRequest(credentialsRequest, profileRequest); } - } From 16f45b4fdd58780f9eefe43f0580aea006822f97 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 14 Jan 2016 15:18:05 -0300 Subject: [PATCH 22/89] Add Authentication class to wrap an AuthenticationRequest result. This is mainly to allow making AuthenticationRequest and SignUpRequest implement the Request<> interface and standardize the way requests work --- .../auth0/authentication/Authentication.java | 48 +++++++++++++++++++ .../authentication/AuthenticationRequest.java | 9 ++-- .../auth0/authentication/SignUpRequest.java | 7 +-- 3 files changed, 57 insertions(+), 7 deletions(-) create mode 100644 core/src/main/java/com/auth0/authentication/Authentication.java diff --git a/core/src/main/java/com/auth0/authentication/Authentication.java b/core/src/main/java/com/auth0/authentication/Authentication.java new file mode 100644 index 00000000..bfa1822c --- /dev/null +++ b/core/src/main/java/com/auth0/authentication/Authentication.java @@ -0,0 +1,48 @@ +/* + * Authentication.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.authentication; + + +import com.auth0.Token; +import com.auth0.UserProfile; + +public class Authentication { + + private final UserProfile profile; + private final Token token; + + public Authentication(UserProfile profile, Token token) { + this.profile = profile; + this.token = token; + } + + public UserProfile getProfile() { + return profile; + } + + public Token getToken() { + return token; + } +} diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index c76d8484..8f3e9218 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -26,7 +26,7 @@ import com.auth0.authentication.api.ParameterBuilder; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.callback.AuthenticationCallback; +import com.auth0.authentication.api.Request; import com.auth0.authentication.api.callback.BaseCallback; import com.auth0.Token; import com.auth0.UserProfile; @@ -36,7 +36,7 @@ /** * Represent a Authentication request that consist of a log in and a fetch profile requests */ -public class AuthenticationRequest { +public class AuthenticationRequest implements Request { private final ParameterizableRequest credentialsRequest; private final ParameterizableRequest tokenInfoRequest; @@ -80,7 +80,8 @@ public AuthenticationRequest setConnection(String connection) { * Starts the log in request and then fetches the user's profile * @param callback called on either success or failure */ - public void start(final AuthenticationCallback callback) { + @Override + public void start(final BaseCallback callback) { credentialsRequest.start(new BaseCallback() { @Override public void onSuccess(final Token token) { @@ -93,7 +94,7 @@ public void onSuccess(final Token token) { .start(new BaseCallback() { @Override public void onSuccess(UserProfile profile) { - callback.onSuccess(profile, token); + callback.onSuccess(new Authentication(profile, token)); } @Override diff --git a/core/src/main/java/com/auth0/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/authentication/SignUpRequest.java index 726c8a19..601903c1 100644 --- a/core/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -25,7 +25,7 @@ package com.auth0.authentication; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.callback.AuthenticationCallback; +import com.auth0.authentication.api.Request; import com.auth0.authentication.api.callback.BaseCallback; import com.auth0.DatabaseUser; @@ -34,7 +34,7 @@ /** * Represent a request to create a user + log in + fetch user profile. */ -public class SignUpRequest { +public class SignUpRequest implements Request { private final ParameterizableRequest signUpRequest; private final AuthenticationRequest authenticationRequest; @@ -88,7 +88,8 @@ public SignUpRequest setConnection(String connection) { * Starts to execute create user request and then logs the user in. * @param callback called on either success or failure. */ - public void start(final AuthenticationCallback callback) { + @Override + public void start(final BaseCallback callback) { signUpRequest.start(new BaseCallback() { @Override public void onSuccess(final DatabaseUser user) { From f3483d4ef2cf86a03368861b5f5fc9ac83a0edb6 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 14 Jan 2016 15:22:43 -0300 Subject: [PATCH 23/89] Add Delegation class that wraps a DelegationRequest result. Is generic to allow using it with fully defined responses (like Auth0 delegations) or with any kind of delegation (use a Map) This also allows us to make DelegationRequest implement the Request<> interface and make it work like any other request --- .../AuthenticationAPIClient.java | 62 +++++++++++++++++-- .../com/auth0/authentication/Delegation.java | 62 +++++++++++++++++++ .../authentication/DelegationRequest.java | 47 +++++--------- 3 files changed, 132 insertions(+), 39 deletions(-) create mode 100644 core/src/main/java/com/auth0/authentication/Delegation.java diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 18affb04..58ab3cd5 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -289,14 +289,15 @@ public ChangePasswordRequest changePassword(String email) { * @param idToken issued by Auth0 for the user. The token must not be expired. * @return a request to configure and start */ - public DelegationRequest delegationWithIdToken(String idToken) { + public DelegationRequest delegationWithIdToken(String idToken) { Map parameters = new ParameterBuilder() .clearAll() .set(ID_TOKEN_KEY, idToken) .asDictionary(); - ParameterizableRequest> request = delegation() + ParameterizableRequest request = delegation(Delegation.class) .addParameters(parameters); - return new DelegationRequest(request); + return new DelegationRequest<>(request) + .setApiType(DelegationRequest.DEFAULT_API_TYPE); } /** @@ -305,14 +306,50 @@ public DelegationRequest delegationWithIdToken(String idToken) { * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. * @return a request to configure and start */ - public DelegationRequest delegationWithRefreshToken(String refreshToken) { + public DelegationRequest delegationWithRefreshToken(String refreshToken) { Map parameters = new ParameterBuilder() .clearAll() .set(REFRESH_TOKEN_KEY, refreshToken) .asDictionary(); - ParameterizableRequest> request = delegation() + ParameterizableRequest request = delegation(Delegation.class) .addParameters(parameters); - return new DelegationRequest(request); + return new DelegationRequest<>(request) + .setApiType(DelegationRequest.DEFAULT_API_TYPE); + } + + /** + * Performs a delegation request that will yield a delegation token. + * @param idToken issued by Auth0 for the user. The token must not be expired. + * @param apiType the delegation 'api_type' parameter + * @return a request to configure and start + */ + public DelegationRequest> delegationWithIdToken(String idToken, String apiType) { + Map parameters = new ParameterBuilder() + .clearAll() + .set(ID_TOKEN_KEY, idToken) + .asDictionary(); + ParameterizableRequest> request = delegation() + .addParameters(parameters); + return new DelegationRequest<>(request) + .setApiType(apiType); + } + + /** + * Performs a delegation request that will yield a delegation token. + * Check our refresh token docs for more information + * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. + * @param apiType the delegation 'api_type' parameter + * @return a request to configure and start + */ + public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { + Map parameters = new ParameterBuilder() + .clearAll() + .set(REFRESH_TOKEN_KEY, refreshToken) + .asDictionary(); + ParameterizableRequest> request = delegation() + .addParameters(parameters); + return new DelegationRequest<>(request) + .setApiType(apiType); } /** @@ -382,6 +419,19 @@ protected ParameterizableRequest> delegation() { .addParameters(parameters); } + protected ParameterizableRequest delegation(Class clazz) { + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment("delegation") + .build(); + Map parameters = ParameterBuilder.newEmptyBuilder() + .clearAll() + .setClientId(getClientId()) + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) + .asDictionary(); + return RequestFactory.POST(url, client, mapper, clazz) + .addParameters(parameters); + } + protected ParameterizableRequest passwordless() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("passwordless") diff --git a/core/src/main/java/com/auth0/authentication/Delegation.java b/core/src/main/java/com/auth0/authentication/Delegation.java new file mode 100644 index 00000000..6dda3032 --- /dev/null +++ b/core/src/main/java/com/auth0/authentication/Delegation.java @@ -0,0 +1,62 @@ +/* + * Delegation.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0.authentication; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import static com.auth0.authentication.api.util.CheckHelper.checkArgument; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Delegation { + private final String idToken; + private final String type; + private final Integer expiresIn; + + @JsonCreator + public Delegation(@JsonProperty(value = "id_token") String idToken, + @JsonProperty(value = "token_type") String type, + @JsonProperty(value = "expires_in") Integer expiresIn) { + checkArgument(idToken != null, "id_token must be non-null"); + checkArgument(type != null, "token_type must be non-null"); + checkArgument(expiresIn != null, "expires_in must be non-null"); + this.idToken = idToken; + this.type = type; + this.expiresIn = expiresIn; + } + + public String getIdToken() { + return idToken; + } + + public String getType() { + return type; + } + + public Integer getExpiresIn() { + return expiresIn; + } +} diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index ef0f37ce..d802ba43 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -26,8 +26,8 @@ import com.auth0.authentication.api.ParameterBuilder; import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.authentication.api.Request; import com.auth0.authentication.api.callback.BaseCallback; -import com.auth0.authentication.api.callback.RefreshIdTokenCallback; import java.util.HashMap; import java.util.Map; @@ -35,29 +35,23 @@ /** * Represent a delegation request for Auth0 tokens that will yield a new 'id_token' */ -public class DelegationRequest { - - private static final String TOKEN_TYPE_KEY = "token_type"; - private static final String EXPIRES_IN_KEY = "expires_in"; - private static final String ID_TOKEN_KEY = "id_token"; +public class DelegationRequest implements Request { private static final String API_TYPE_KEY = "api_type"; - private static final String DEFAULT_API_TYPE = "app"; + public static final String DEFAULT_API_TYPE = "app"; private static final String TARGET_KEY = "target"; - private final ParameterizableRequest> request; + private final ParameterizableRequest request; - DelegationRequest(ParameterizableRequest> request) { + DelegationRequest(ParameterizableRequest request) { this.request = request; - addParameter(API_TYPE_KEY, DEFAULT_API_TYPE); } - private DelegationRequest addParameter(String key, Object value) { + private DelegationRequest addParameter(String key, Object value) { Map parameters = new HashMap<>(); parameters.put(key, value); - request.addParameters(parameters); - return this; + return addParameters(parameters); } /** @@ -65,7 +59,7 @@ private DelegationRequest addParameter(String key, Object value) { * @param parameters as a non-null dictionary * @return itself */ - public DelegationRequest addParameters(Map parameters) { + public DelegationRequest addParameters(Map parameters) { request.addParameters(parameters); return this; } @@ -75,7 +69,7 @@ public DelegationRequest addParameters(Map parameters) { * @param apiType the delegation api type * @return itself */ - public DelegationRequest setApiType(String apiType) { + public DelegationRequest setApiType(String apiType) { return addParameter(API_TYPE_KEY, apiType); } @@ -84,7 +78,7 @@ public DelegationRequest setApiType(String apiType) { * @param scope value * @return itself */ - public DelegationRequest setScope(String scope) { + public DelegationRequest setScope(String scope) { return addParameters(new ParameterBuilder().clearAll().setScope(scope).asDictionary()); } @@ -93,7 +87,7 @@ public DelegationRequest setScope(String scope) { * @param target the delegation target * @return itself */ - public DelegationRequest setTarget(String target) { + public DelegationRequest setTarget(String target) { return addParameter(TARGET_KEY, target); } @@ -101,21 +95,8 @@ public DelegationRequest setTarget(String target) { * Performs the HTTP request against Auth0 API * @param callback called either on success or failure */ - public void start(final RefreshIdTokenCallback callback) { - request.start(new BaseCallback>() { - @Override - public void onSuccess(final Map payload) { - final String id_token = (String) payload.get(ID_TOKEN_KEY); - final String token_type = (String) payload.get(TOKEN_TYPE_KEY); - final Integer expires_in = (Integer) payload.get(EXPIRES_IN_KEY); - callback.onSuccess(id_token, token_type, expires_in); - } - - @Override - public void onFailure(Throwable error) { - callback.onFailure(error); - } - }); + @Override + public void start(final BaseCallback callback) { + request.start(callback); } - } From f0518faa01bbe15ef94d1b102c40104ad436d29f Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Fri, 15 Jan 2016 14:49:44 -0300 Subject: [PATCH 24/89] Fix tests. Adapt them to use new Authentication and Delegation responses --- .../AuthenticationAPIClientTest.java | 43 +++++----- .../util/AuthenticationCallbackMatcher.java | 79 ------------------- .../api/util/MockAuthenticationCallback.java | 76 ------------------ .../api/util/MockRefreshIdTokenCallback.java | 36 --------- 4 files changed, 18 insertions(+), 216 deletions(-) delete mode 100644 core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java delete mode 100644 core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java delete mode 100644 core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 9eb4e653..cb4348e3 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -32,9 +32,7 @@ import com.auth0.Token; import com.auth0.UserProfile; import com.auth0.authentication.api.util.AuthenticationAPI; -import com.auth0.authentication.api.util.MockAuthenticationCallback; import com.auth0.authentication.api.util.MockBaseCallback; -import com.auth0.authentication.api.util.MockRefreshIdTokenCallback; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.mockwebserver.RecordedRequest; @@ -48,9 +46,7 @@ import static com.auth0.authentication.api.util.AuthenticationAPI.GENERIC_TOKEN; import static com.auth0.authentication.api.util.AuthenticationAPI.ID_TOKEN; -import static com.auth0.authentication.api.util.AuthenticationAPI.NEW_ID_TOKEN; import static com.auth0.authentication.api.util.AuthenticationAPI.REFRESH_TOKEN; -import static com.auth0.authentication.api.util.AuthenticationCallbackMatcher.hasTokenAndProfile; import static com.auth0.authentication.api.util.CallbackMatcher.hasNoError; import static com.auth0.authentication.api.util.CallbackMatcher.hasNoPayloadOfType; import static com.auth0.authentication.api.util.CallbackMatcher.hasPayload; @@ -187,12 +183,12 @@ public void shouldLoginWithUserAndPassword() throws Exception { mockAPI .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.login("support@auth0.com", "voidpassword") .start(callback); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -215,7 +211,7 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithOAuthAccessToken("fbtoken", "facebook") .start(callback); @@ -227,7 +223,7 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { assertThat(body, hasEntry("access_token", "fbtoken")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -236,7 +232,7 @@ public void shouldLoginWithPhoneNumber() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithPhoneNumber("+10101010101", "1234") .start(callback); @@ -249,7 +245,7 @@ public void shouldLoginWithPhoneNumber() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -258,7 +254,7 @@ public void shouldLoginWithEmailOnly() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithEmail("support@auth0.com", "1234") .start(callback); @@ -271,7 +267,7 @@ public void shouldLoginWithEmailOnly() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -319,7 +315,7 @@ public void shouldSignUpUser() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123", "support") .start(callback); @@ -331,7 +327,7 @@ public void shouldSignUpUser() throws Exception { assertThat(body, hasEntry("username", "support")); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -340,7 +336,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockAuthenticationCallback callback = new MockAuthenticationCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123") .start(callback); @@ -352,7 +348,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { assertThat(body, not(hasEntry("username", "support"))); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasTokenAndProfile()); + assertThat(callback, hasPayloadOfType(Authentication.class)); } @Test @@ -418,7 +414,7 @@ public void shouldCallDelegation() throws Exception { public void shouldGetNewIdTokenWithIdToken() throws Exception { mockAPI.willReturnNewIdToken(); - final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.delegationWithIdToken(ID_TOKEN) .start(callback); @@ -431,14 +427,14 @@ public void shouldGetNewIdTokenWithIdToken() throws Exception { assertThat(body, hasEntry("api_type", "app")); assertThat(body, hasEntry("id_token", ID_TOKEN)); - assertThat(callback, hasPayload(NEW_ID_TOKEN)); + assertThat(callback, hasPayloadOfType(Delegation.class)); } @Test public void shouldGetNewIdTokenWithRefreshToken() throws Exception { mockAPI.willReturnNewIdToken(); - final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.delegationWithRefreshToken(REFRESH_TOKEN) .start(callback); @@ -451,16 +447,15 @@ public void shouldGetNewIdTokenWithRefreshToken() throws Exception { assertThat(body, hasEntry("api_type", "app")); assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); - assertThat(callback, hasPayload(NEW_ID_TOKEN)); + assertThat(callback, hasPayloadOfType(Delegation.class)); } @Test public void shouldGetCustomizedDelegationRequest() throws Exception { mockAPI.willReturnNewIdToken(); - final MockRefreshIdTokenCallback callback = new MockRefreshIdTokenCallback(); - client.delegationWithRefreshToken(REFRESH_TOKEN) - .setApiType("custom_api_type") + final MockBaseCallback> callback = new MockBaseCallback<>(); + client.delegationWithRefreshToken(REFRESH_TOKEN, "custom_api_type") .setScope("custom_scope") .setTarget("custom_target") .start(callback); @@ -475,8 +470,6 @@ public void shouldGetCustomizedDelegationRequest() throws Exception { assertThat(body, hasEntry("scope", "custom_scope")); assertThat(body, hasEntry("target", "custom_target")); assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); - - assertThat(callback, hasPayload(NEW_ID_TOKEN)); } @Test diff --git a/core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java b/core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java deleted file mode 100644 index bc4875f4..00000000 --- a/core/src/test/java/com/auth0/authentication/api/util/AuthenticationCallbackMatcher.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * AuthenticationCallbackMatcher.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.util; - -import com.auth0.Token; -import com.auth0.UserProfile; -import com.jayway.awaitility.core.ConditionTimeoutException; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import static com.jayway.awaitility.Awaitility.await; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; - -public class AuthenticationCallbackMatcher extends BaseMatcher { - - private final Matcher tokenMatcher; - private final Matcher profileMatcher; - private final Matcher errorMatcher; - - public AuthenticationCallbackMatcher(Matcher tokenMatcher, Matcher profileMatcher, Matcher errorMatcher) { - this.tokenMatcher = tokenMatcher; - this.profileMatcher = profileMatcher; - this.errorMatcher = errorMatcher; - } - - @Override - public boolean matches(Object item) { - MockAuthenticationCallback callback = (MockAuthenticationCallback) item; - try { - await().until(callback.token(), tokenMatcher); - await().until(callback.profile(), profileMatcher); - await().until(callback.error(), errorMatcher); - return true; - } catch (ConditionTimeoutException e) { - return false; - } - } - - @Override - public void describeTo(Description description) { - description - .appendText("successful method be called"); - } - - public static Matcher hasTokenAndProfile() { - return new AuthenticationCallbackMatcher(is(notNullValue(Token.class)), is(notNullValue(UserProfile.class)), is(nullValue(Throwable.class))); - } - - public static Matcher hasNeitherTokeNorProfile() { - return new AuthenticationCallbackMatcher(is(nullValue(Token.class)), is(nullValue(UserProfile.class)), is(notNullValue(Throwable.class))); - } - -} diff --git a/core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java deleted file mode 100644 index d90d65c7..00000000 --- a/core/src/test/java/com/auth0/authentication/api/util/MockAuthenticationCallback.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * MockAuthenticationCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.util; - -import com.auth0.authentication.api.callback.AuthenticationCallback; -import com.auth0.Token; -import com.auth0.UserProfile; - -import java.util.concurrent.Callable; - -public class MockAuthenticationCallback implements AuthenticationCallback { - - private Token token; - private UserProfile profile; - private Throwable error; - - @Override - public void onSuccess(UserProfile profile, Token token) { - this.token = token; - this.profile = profile; - } - - @Override - public void onFailure(Throwable error) { - this.error = error; - } - - public Callable token() { - return new Callable() { - @Override - public Token call() throws Exception { - return token; - } - }; - } - - public Callable profile() { - return new Callable() { - @Override - public UserProfile call() throws Exception { - return profile; - } - }; - } - - public Callable error() { - return new Callable() { - @Override - public Throwable call() throws Exception { - return error; - } - }; - } -} diff --git a/core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java deleted file mode 100644 index 2a8a7233..00000000 --- a/core/src/test/java/com/auth0/authentication/api/util/MockRefreshIdTokenCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * MockRefreshIdTokenCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.util; - -import com.auth0.authentication.api.callback.RefreshIdTokenCallback; - -public class MockRefreshIdTokenCallback extends MockBaseCallback implements RefreshIdTokenCallback { - - @Override - public void onSuccess(String idToken, String tokenType, int expiresIn) { - onSuccess(idToken); - } - -} From 4895dffdd9491c4e17503387349f9f38dedb3e90 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Fri, 15 Jan 2016 14:50:37 -0300 Subject: [PATCH 25/89] Add check of the constructor parameters. They can't be null --- .../main/java/com/auth0/authentication/Authentication.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/src/main/java/com/auth0/authentication/Authentication.java b/core/src/main/java/com/auth0/authentication/Authentication.java index bfa1822c..c04c64dd 100644 --- a/core/src/main/java/com/auth0/authentication/Authentication.java +++ b/core/src/main/java/com/auth0/authentication/Authentication.java @@ -28,12 +28,16 @@ import com.auth0.Token; import com.auth0.UserProfile; +import static com.auth0.authentication.api.util.CheckHelper.checkArgument; + public class Authentication { private final UserProfile profile; private final Token token; public Authentication(UserProfile profile, Token token) { + checkArgument(profile != null, "profile must be non-null"); + checkArgument(token != null, "token must be non-null"); this.profile = profile; this.token = token; } From 36a1f668a96b6b8f0905d68106e820b479b339fb Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 18 Jan 2016 17:01:08 -0300 Subject: [PATCH 26/89] Add javadoc to Authentication and Delegation classes --- .../auth0/authentication/Authentication.java | 4 ++++ .../com/auth0/authentication/Delegation.java | 23 ++++++++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/Authentication.java b/core/src/main/java/com/auth0/authentication/Authentication.java index c04c64dd..4467991c 100644 --- a/core/src/main/java/com/auth0/authentication/Authentication.java +++ b/core/src/main/java/com/auth0/authentication/Authentication.java @@ -30,6 +30,10 @@ import static com.auth0.authentication.api.util.CheckHelper.checkArgument; +/** + * The result of a successful authentication against Auth0 + * Contains the logged in user's {@link Token} and {@link UserProfile} + */ public class Authentication { private final UserProfile profile; diff --git a/core/src/main/java/com/auth0/authentication/Delegation.java b/core/src/main/java/com/auth0/authentication/Delegation.java index 6dda3032..297480cc 100644 --- a/core/src/main/java/com/auth0/authentication/Delegation.java +++ b/core/src/main/java/com/auth0/authentication/Delegation.java @@ -30,16 +30,21 @@ import static com.auth0.authentication.api.util.CheckHelper.checkArgument; +/** + * The result of a successful delegation to an Auth0 app. + * Contains a new Auth0 'id_token' to be used on the 'target' app + * See delegation docs + */ @JsonIgnoreProperties(ignoreUnknown = true) public class Delegation { private final String idToken; private final String type; - private final Integer expiresIn; + private final Long expiresIn; @JsonCreator public Delegation(@JsonProperty(value = "id_token") String idToken, @JsonProperty(value = "token_type") String type, - @JsonProperty(value = "expires_in") Integer expiresIn) { + @JsonProperty(value = "expires_in") Long expiresIn) { checkArgument(idToken != null, "id_token must be non-null"); checkArgument(type != null, "token_type must be non-null"); checkArgument(expiresIn != null, "expires_in must be non-null"); @@ -48,15 +53,27 @@ public Delegation(@JsonProperty(value = "id_token") String idToken, this.expiresIn = expiresIn; } + /** + * Id token + * @return the 'id_token' value + */ public String getIdToken() { return idToken; } + /** + * Token type + * @return the 'token_type' value + */ public String getType() { return type; } - public Integer getExpiresIn() { + /** + * Token expire time in milliseconds since January 1, 1970, 00:00:00 GMT + * @return the 'expires_in' value + */ + public Long getExpiresIn() { return expiresIn; } } From 40c912addded09c73e025e3cfe625d6a7e903c96 Mon Sep 17 00:00:00 2001 From: lbalmaceda Date: Tue, 19 Jan 2016 10:45:59 -0300 Subject: [PATCH 27/89] add .travis.yml file --- .travis.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..547ab29e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +language: java + +jdk: + - oraclejdk7 + - openjdk7 + +before_install: + - chmod +x gradlew + +script: + - ./gradlew check From 7be1a6c1dd9c80262c23b8ccc62f4d102a63e5fc Mon Sep 17 00:00:00 2001 From: lbalmaceda Date: Tue, 19 Jan 2016 11:00:08 -0300 Subject: [PATCH 28/89] run travis only on master branch. continue if a single test fails --- .travis.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 547ab29e..2e1c7900 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,8 @@ before_install: - chmod +x gradlew script: - - ./gradlew check + - ./gradlew clean check --continue + +branches: + only: + - master From fbb8d6917e8e14901f80ea9f901f2abff32cac84 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 19 Jan 2016 13:50:51 -0300 Subject: [PATCH 29/89] Add Slack notification --- .travis.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2e1c7900..cda8249e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,14 @@ language: java - jdk: - - oraclejdk7 - - openjdk7 - +- oraclejdk7 +- openjdk7 before_install: - - chmod +x gradlew - +- chmod +x gradlew script: - - ./gradlew clean check --continue - +- "./gradlew clean check --continue" branches: only: - master +notifications: + slack: + secure: kwwYDhmQFZ0wJFkPQurni7litDbloU3LqFlQ+0ZqvM8ZFuh1vBVE2E0T2it58RjugitH0RpI8HeRki8rBbt38Pz33MPDp8HOQM5GU7jhxImALQ3dDVT7ji2GfIZdoZR5sXL/XkawwGkols/fQk5WjGAIKjTtSn99GOU5MiZLQ11ajOr9bNUg6o1fBEa30edo5cXmYv39ELrNq+o3GaCPoq5ggBQoRS1/DfyHNh1kHbrtTRNMdEF77ANkZ7V0BevWmVMapRwWnZ3kCKJCKLcWdUl7EDcBDHI4mWANJGwj0kGf9e7HuNuO3UjLFmmPjCuIyB5j7bEjKBDfifQynzX0SmJYx5XBIO66NGLePzoqX2me8/CG8S23rkQcrgwHcCvtu2UavIiOT6iYNFy3CcJYXsaMkOcRP9l6I0FHYoUGunkHGBkpvhlDUnF4nQ9d/Ti6mb/SCe6/2X9+zvHJBN33+GaLCeNLe8ttoEOaFj0exupdzqKvjnZ552wmKb+7gjjdiXixq6hmPnkLOtYevVlk8arnjE6p7ZQF1efIavSPga6ypydScKRprT+Qexy7mFO12XxISew/k8jHAHr1cjK+L1C4buiI9vPtN2k1xKqs8EX9iaDHVNl94bVJLv9H/AN7vysDcadlczyxSyWQ5ZuyUPYBKC9CC4F8NBRGNaYkjIs= From 5db35f05fd9a75779bbd106b9e0d7e64fdf0147c Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Wed, 13 Jan 2016 11:17:38 -0300 Subject: [PATCH 30/89] Add basic sync mode Include tests for all async tests --- .../authentication/AuthenticationRequest.java | 18 + .../authentication/ChangePasswordRequest.java | 10 + .../authentication/DelegationRequest.java | 10 + .../auth0/authentication/SignUpRequest.java | 11 + .../com/auth0/authentication/api/Request.java | 11 + .../api/internal/ApplicationInfoRequest.java | 70 ++- .../api/internal/SimpleRequest.java | 36 ++ .../api/internal/VoidRequest.java | 34 +- .../AuthenticationAPIClientTest.java | 584 +++++++++++++++++- .../api/internal/BaseRequestTest.java | 5 + 10 files changed, 760 insertions(+), 29 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index 8f3e9218..3b331d19 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -110,4 +110,22 @@ public void onFailure(Throwable error) { } }); } + + /** + * Executes the log in request and then fetches the user's profile + * @return authentication object on success + * @throws Throwable on failure + */ + @Override + public Authentication execute() throws Throwable { + Token token = credentialsRequest.execute(); + Map parameters = new ParameterBuilder() + .clearAll() + .set("id_token", token.getIdToken()) + .asDictionary(); + UserProfile profile = tokenInfoRequest + .addParameters(parameters) + .execute(); + return new Authentication(profile, token); + } } diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index 0e7d01bf..c918ba91 100644 --- a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -89,4 +89,14 @@ public ChangePasswordRequest addHeader(String name, String value) { public void start(final BaseCallback callback) { request.start(callback); } + + /** + * Executes the HTTP request against Auth0 API + * @return Void on success + * @throws Throwable on failure + */ + @Override + public Void execute() throws Throwable { + return request.execute(); + } } diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index d802ba43..a95e5f25 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -99,4 +99,14 @@ public DelegationRequest setTarget(String target) { public void start(final BaseCallback callback) { request.start(callback); } + + /** + * Executes the HTTP request against Auth0 API + * @return the delegation response on success + * @throws Throwable on failure + */ + @Override + public T execute() throws Throwable { + return request.execute(); + } } diff --git a/core/src/main/java/com/auth0/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/authentication/SignUpRequest.java index 601903c1..c7d81d19 100644 --- a/core/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -103,4 +103,15 @@ public void onFailure(Throwable error) { } }); } + + /** + * Execute the create user request and then logs the user in. + * @return authentication object on success + * @throws Throwable on failure + */ + @Override + public Authentication execute() throws Throwable { + signUpRequest.execute(); + return authenticationRequest.execute(); + } } diff --git a/core/src/main/java/com/auth0/authentication/api/Request.java b/core/src/main/java/com/auth0/authentication/api/Request.java index 19c27bf2..8d1d72e0 100644 --- a/core/src/main/java/com/auth0/authentication/api/Request.java +++ b/core/src/main/java/com/auth0/authentication/api/Request.java @@ -32,5 +32,16 @@ */ public interface Request { + /** + * Performs an async HTTP request against Auth0 API + * @param callback called either on success or failure + */ void start(BaseCallback callback); + + /** + * Executes the HTTP request against Auth0 API (blocking the current thread) + * @return the response on success + * @throws Throwable on failure + */ + T execute() throws Throwable; } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index 2d116ad2..81f02c67 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -24,16 +24,16 @@ package com.auth0.authentication.api.internal; +import com.auth0.Application; import com.auth0.authentication.api.APIClientException; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.Application; +import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; - import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; @@ -67,27 +67,10 @@ public void onResponse(Response response) throws IOException { } try { String json = response.body().string(); - if (json.length() < 16) { - throw new JSONException("Failed to parse JSONP"); - } - json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method - JSONTokener tokenizer = new JSONTokener(json); - //tokenizer.skipPast("Auth0.setClient("); - if (!tokenizer.more()) { - postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP")); - return; - } - Object nextValue = tokenizer.nextValue(); - if (!(nextValue instanceof JSONObject)) { - tokenizer.back(); - postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info")); - } - JSONObject jsonObject = (JSONObject) nextValue; - Application app = getReader().readValue(jsonObject.toString()); - + Application app = parseJSONP(json); postOnSuccess(app); - } catch (JSONException | IOException e) { - postOnFailure(new APIClientException("Failed to parse JSONP", e)); + } catch (Throwable e) { + postOnFailure(e); } } @@ -100,4 +83,47 @@ public ParameterizableRequest addParameters(Map par public ParameterizableRequest addHeader(String name, String value) { return this; } + + @Override + public Application execute() throws Throwable { + Request request; + try { + request = doBuildRequest(newBuilder()); + } catch (RequestBodyBuildException e) { + throw new APIClientException("Failed to send request to " + url.toString(), e); + } + + Response response; + try { + response = client.newCall(request).execute(); + } catch (IOException e) { + throw new APIClientException("Failed to execute request to " + url.toString(), e); + } + + if (!response.isSuccessful()) { + String message = "Received app info failed response with code " + response.code() + " and body " + response.body().string(); + throw new IOException(message); + } + + String json = response.body().string(); + return parseJSONP(json); + } + + private Application parseJSONP(String json) throws Throwable { + if (json.length() < 16) { + throw new JSONException("Failed to parse JSONP"); + } + json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method + JSONTokener tokenizer = new JSONTokener(json); + if (!tokenizer.more()) { + throw tokenizer.syntaxError("Invalid App Info JSONP"); + } + Object nextValue = tokenizer.nextValue(); + if (!(nextValue instanceof JSONObject)) { + tokenizer.back(); + throw tokenizer.syntaxError("Invalid JSON value of App Info"); + } + JSONObject jsonObject = (JSONObject) nextValue; + return getReader().readValue(jsonObject.toString()); + } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java index 30d56d61..852a3a2b 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java @@ -89,4 +89,40 @@ protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request .method(method, body) .build(); } + + @Override + public T execute() throws Throwable { + com.squareup.okhttp.Request request; + try { + request = doBuildRequest(newBuilder()); + } catch (RequestBodyBuildException e) { + throw new APIClientException("Failed to send request to " + url.toString(), e); + } + + Response response; + try { + response = client.newCall(request).execute(); + } catch (IOException e) { + throw new APIClientException("Failed to execute request to " + url.toString(), e); + } + + final InputStream byteStream = response.body().byteStream(); + if (!response.isSuccessful()) { + Throwable throwable; + try { + Map payload = errorReader.readValue(byteStream); + throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); + } catch (IOException e) { + throwable = new APIClientException("Request failed", response.code(), null); + } + throw throwable; + } + + try { + T payload = getReader().readValue(byteStream); + return payload; + } catch (IOException e) { + throw new APIClientException("Request failed", response.code(), null); + } + } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java index 73be39e6..bbbc66f5 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java @@ -25,12 +25,14 @@ package com.auth0.authentication.api.internal; import com.auth0.authentication.api.APIClientException; +import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; @@ -69,10 +71,40 @@ public void onResponse(Response response) throws IOException { } @Override - protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request.Builder builder) { + protected Request doBuildRequest(Request.Builder builder) { RequestBody body = buildBody(); return newBuilder() .method(httpMethod, body) .build(); } + + @Override + public Void execute() throws Throwable { + Request request; + try { + request = doBuildRequest(newBuilder()); + } catch (RequestBodyBuildException e) { + throw new APIClientException("Failed to send request to " + url.toString(), e); + } + + Response response; + try { + response = client.newCall(request).execute(); + } catch (IOException e) { + throw new APIClientException("Failed to execute request to " + url.toString(), e); + } + + final InputStream byteStream = response.body().byteStream(); + if (!response.isSuccessful()) { + Throwable throwable; + try { + Map payload = errorReader.readValue(byteStream); + throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); + } catch (IOException e) { + throwable = new APIClientException("Request failed", response.code(), null); + } + throw throwable; + } + return null; + } } diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index cb4348e3..c1bb064f 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -51,12 +51,7 @@ import static com.auth0.authentication.api.util.CallbackMatcher.hasNoPayloadOfType; import static com.auth0.authentication.api.util.CallbackMatcher.hasPayload; import static com.auth0.authentication.api.util.CallbackMatcher.hasPayloadOfType; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; public class AuthenticationAPIClientTest { @@ -102,6 +97,18 @@ public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { assertThat(callback, hasPayloadOfType(Application.class)); } + @Test + public void shouldLoadApplicationInfoFromConfigurationUrlSync() throws Throwable { + mockAPI.willReturnValidApplicationResponse(); + + final Application application = client + .fetchApplicationInfo() + .execute(); + + assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); + assertThat(application, is(notNullValue())); + } + @Test public void shoulFailWithInvalidJSON() throws Exception { mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); @@ -111,6 +118,22 @@ public void shoulFailWithInvalidJSON() throws Exception { assertThat(callback, hasNoPayloadOfType(Application.class)); } + @Test + public void shoulFailWithInvalidJSONSync() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); + + Throwable throwable = null; + try { + client + .fetchApplicationInfo() + .execute(); + } catch (Throwable e) { + throwable = e; + } + + assertThat(throwable, is(notNullValue())); + } + @Test public void shoulFailWithInvalidJSONP() throws Exception { mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); @@ -120,6 +143,22 @@ public void shoulFailWithInvalidJSONP() throws Exception { assertThat(callback, hasNoPayloadOfType(Application.class)); } + @Test + public void shoulFailWithInvalidJSONPSync() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); + + Throwable throwable = null; + try { + client + .fetchApplicationInfo() + .execute(); + } catch (Throwable e) { + throwable = e; + } + + assertThat(throwable, is(notNullValue())); + } + @Test public void shouldFailWithFailedStatusCode() throws Exception { mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); @@ -131,6 +170,22 @@ public void shouldFailWithFailedStatusCode() throws Exception { assertThat(callback, hasNoPayloadOfType(Application.class)); } + @Test + public void shouldFailWithFailedStatusCodeSync() throws Exception { + mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); + + Throwable throwable = null; + try { + client + .fetchApplicationInfo() + .execute(); + } catch (Throwable e) { + throwable = e; + } + + assertThat(throwable, is(notNullValue())); + } + @Test public void shouldLoginWithResourceOwner() throws Exception { mockAPI.willReturnSuccessfulLogin(); @@ -160,6 +215,36 @@ public void shouldLoginWithResourceOwner() throws Exception { assertThat(body, hasEntry("scope", "openid")); } + @Test + public void shouldLoginWithResourceOwnerSync() throws Throwable { + mockAPI.willReturnSuccessfulLogin(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection("DB") + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .setScope(ParameterBuilder.SCOPE_OPENID) + .asDictionary(); + + final Token token = client + .loginWithResourceOwner() + .addParameters(parameters) + .execute(); + + assertThat(token, is(notNullValue())); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "DB")); + assertThat(body, hasEntry("grant_type", "password")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "notapassword")); + assertThat(body, hasEntry("scope", "openid")); + } + @Test public void shouldFailLoginWithResourceOwner() throws Exception { mockAPI.willReturnFailedLogin(); @@ -178,6 +263,30 @@ public void shouldFailLoginWithResourceOwner() throws Exception { assertThat(callback, hasNoPayloadOfType(Token.class)); } + @Test + public void shouldFailLoginWithResourceOwnerSync() throws Exception { + mockAPI.willReturnFailedLogin(); + final MockBaseCallback callback = new MockBaseCallback<>(); + + final Map parameters = ParameterBuilder.newBuilder() + .setConnection(CONNECTION) + .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) + .set("username", "support@auth0.com") + .set("password", "notapassword") + .asDictionary(); + + Throwable throwable = null; + try { + client.loginWithResourceOwner() + .addParameters(parameters) + .execute(); + } catch (Throwable e) { + throwable = e; + } + + assertThat(throwable, is(notNullValue())); + } + @Test public void shouldLoginWithUserAndPassword() throws Exception { mockAPI @@ -191,6 +300,19 @@ public void shouldLoginWithUserAndPassword() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldLoginWithUserAndPasswordSync() throws Throwable { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .login("support@auth0.com", "voidpassword") + .execute(); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldFetchTokenInfo() throws Exception { mockAPI.willReturnTokenInfo(); @@ -205,6 +327,20 @@ public void shouldFetchTokenInfo() throws Exception { assertThat(request.getPath(), equalTo("/tokeninfo")); } + @Test + public void shouldFetchTokenInfoSync() throws Throwable { + mockAPI.willReturnTokenInfo(); + + final UserProfile profile = client + .tokenInfo("ID_TOKEN") + .execute(); + + assertThat(profile, is(notNullValue())); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/tokeninfo")); + } + @Test public void shouldLoginWithOAuthAccessToken() throws Exception { mockAPI @@ -226,6 +362,27 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldLoginWithOAuthAccessTokenSync() throws Throwable { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .loginWithOAuthAccessToken("fbtoken", "facebook") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/access_token")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "facebook")); + assertThat(body, hasEntry("access_token", "fbtoken")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldLoginWithPhoneNumber() throws Exception { mockAPI @@ -248,6 +405,28 @@ public void shouldLoginWithPhoneNumber() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldLoginWithPhoneNumberSync() throws Throwable { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .loginWithPhoneNumber("+10101010101", "1234") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "sms")); + assertThat(body, hasEntry("username", "+10101010101")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldLoginWithEmailOnly() throws Exception { mockAPI @@ -270,6 +449,28 @@ public void shouldLoginWithEmailOnly() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldLoginWithEmailOnlySync() throws Throwable { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .loginWithEmail("support@auth0.com", "1234") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("connection", "email")); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "1234")); + assertThat(body, hasEntry("scope", "openid offline_access")); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldCreateUser() throws Exception { mockAPI.willReturnSuccessfulSignUp(); @@ -287,7 +488,25 @@ public void shouldCreateUser() throws Exception { assertThat(body, hasEntry("password", "123123123")); assertThat(callback, hasPayloadOfType(DatabaseUser.class)); + } + + @Test + public void shouldCreateUserSync() throws Throwable { + mockAPI.willReturnSuccessfulSignUp(); + final DatabaseUser user = client + .createUser("support@auth0.com", "123123123", "support") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(user, is(notNullValue())); } @Test @@ -309,6 +528,25 @@ public void shouldCreateUserWithoutUsername() throws Exception { assertThat(callback, hasPayloadOfType(DatabaseUser.class)); } + @Test + public void shouldCreateUserWithoutUsernameSync() throws Throwable { + mockAPI.willReturnSuccessfulSignUp(); + + final DatabaseUser user = client + .createUser("support@auth0.com", "123123123") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", null)); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(user, is(notNullValue())); + } + @Test public void shouldSignUpUser() throws Exception { mockAPI.willReturnSuccessfulSignUp() @@ -330,6 +568,27 @@ public void shouldSignUpUser() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldSignUpUserSync() throws Throwable { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .signUp("support@auth0.com", "123123123", "support") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", "support")); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldSignUpUserWithoutUsername() throws Exception { mockAPI.willReturnSuccessfulSignUp() @@ -351,6 +610,27 @@ public void shouldSignUpUserWithoutUsername() throws Exception { assertThat(callback, hasPayloadOfType(Authentication.class)); } + @Test + public void shouldSignUpUserWithoutUsernameSync() throws Throwable { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + final Authentication authentication = client + .signUp("support@auth0.com", "123123123") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("username", null)); + assertThat(body, hasEntry("password", "123123123")); + + assertThat(authentication, is(notNullValue())); + } + @Test public void shouldChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); @@ -371,6 +651,23 @@ public void shouldChangePassword() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldChangePasswordSync() throws Throwable { + mockAPI.willReturnSuccessfulChangePassword(); + + client.changePassword("support@auth0.com") + .setNewPassword("123123123") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasKey("username"))); + assertThat(body, hasEntry("password", "123123123")); + } + @Test public void shouldRequestChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); @@ -390,6 +687,22 @@ public void shouldRequestChangePassword() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldRequestChangePasswordSync() throws Throwable { + mockAPI.willReturnSuccessfulChangePassword(); + + client.changePassword("support@auth0.com") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, not(hasKey("username"))); + assertThat(body, not(hasKey("password"))); + } + @Test public void shouldCallDelegation() throws Exception { mockAPI.willReturnGenericDelegationToken(); @@ -410,6 +723,26 @@ public void shouldCallDelegation() throws Exception { assertThat(callback, hasPayload(payload)); } + @Test + public void shouldCallDelegationSync() throws Throwable { + mockAPI.willReturnGenericDelegationToken(); + + final Map response = client + .delegation() + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + + Map payload = new HashMap<>(); + payload.put("token", GENERIC_TOKEN); + assertThat(response, is(equalTo(payload))); + } + @Test public void shouldGetNewIdTokenWithIdToken() throws Exception { mockAPI.willReturnNewIdToken(); @@ -430,6 +763,26 @@ public void shouldGetNewIdTokenWithIdToken() throws Exception { assertThat(callback, hasPayloadOfType(Delegation.class)); } + @Test + public void shouldGetNewIdTokenWithIdTokenSync() throws Throwable { + mockAPI.willReturnNewIdToken(); + + final Delegation delegation = client + .delegationWithIdToken(ID_TOKEN) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("id_token", ID_TOKEN)); + + assertThat(delegation, is(notNullValue())); + } + @Test public void shouldGetNewIdTokenWithRefreshToken() throws Exception { mockAPI.willReturnNewIdToken(); @@ -450,6 +803,26 @@ public void shouldGetNewIdTokenWithRefreshToken() throws Exception { assertThat(callback, hasPayloadOfType(Delegation.class)); } + @Test + public void shouldGetNewIdTokenWithRefreshTokenSync() throws Throwable { + mockAPI.willReturnNewIdToken(); + + final Delegation delegation = client + .delegationWithRefreshToken(REFRESH_TOKEN) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "app")); + assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); + + assertThat(delegation, is(notNullValue())); + } + @Test public void shouldGetCustomizedDelegationRequest() throws Exception { mockAPI.willReturnNewIdToken(); @@ -472,6 +845,28 @@ public void shouldGetCustomizedDelegationRequest() throws Exception { assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); } + @Test + public void shouldGetCustomizedDelegationRequestSync() throws Throwable { + mockAPI.willReturnNewIdToken(); + + client + .delegationWithRefreshToken(REFRESH_TOKEN, "custom_api_type") + .setScope("custom_scope") + .setTarget("custom_target") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "custom_api_type")); + assertThat(body, hasEntry("scope", "custom_scope")); + assertThat(body, hasEntry("target", "custom_target")); + assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); + } + @Test public void shouldUnlinkAccount() throws Exception { mockAPI.willReturnSuccessfulUnlinkAccount(); @@ -491,6 +886,22 @@ public void shouldUnlinkAccount() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldUnlinkAccountSync() throws Throwable { + mockAPI.willReturnSuccessfulUnlinkAccount(); + + client.unlink("user id", "access token") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/unlink")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("clientID", CLIENT_ID)); + assertThat(body, hasEntry("user_id", "user id")); + assertThat(body, hasEntry("access_token", "access token")); + } + @Test public void shouldStartPasswordless() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -518,6 +929,31 @@ public void shouldStartPasswordless() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldStartPasswordlessSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + final Map parameters = new ParameterBuilder() + .clearAll() + .setConnection("email") + .set("send", "code") + .set("email", "support@auth0.com") + .asDictionary(); + + client.passwordless() + .addParameters(parameters) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + } + @Test public void shouldSendEmailCode() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -538,6 +974,23 @@ public void shouldSendEmailCode() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendEmailCodeSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.CODE) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "email")); + } + @Test public void shouldSendEmailLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -558,6 +1011,23 @@ public void shouldSendEmailLink() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendEmailLinkSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link")); + assertThat(body, hasEntry("connection", "email")); + } + @Test public void shouldSendEmailLinkAndroid() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -578,6 +1048,23 @@ public void shouldSendEmailLinkAndroid() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendEmailLinkAndroidSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_ANDROID) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "email")); + } + @Test public void shouldSendEmailLinkIOS() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -598,6 +1085,23 @@ public void shouldSendEmailLinkIOS() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendEmailLinkIOSSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_IOS) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("send", "link_ios")); + assertThat(body, hasEntry("connection", "email")); + } + @Test public void shouldSendSMSCode() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -618,6 +1122,23 @@ public void shouldSendSMSCode() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendSMSCodeSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithSMS("+1123123123", PasswordlessType.CODE) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "code")); + assertThat(body, hasEntry("connection", "sms")); + } + @Test public void shouldSendSMSLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -638,6 +1159,23 @@ public void shouldSendSMSLink() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendSMSLinkSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link")); + assertThat(body, hasEntry("connection", "sms")); + } + @Test public void shouldSendSMSLinkAndroid() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -658,6 +1196,23 @@ public void shouldSendSMSLinkAndroid() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendSMSLinkAndroidSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_ANDROID) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link_android")); + assertThat(body, hasEntry("connection", "sms")); + } + @Test public void shouldSendSMSLinkIOS() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); @@ -678,6 +1233,23 @@ public void shouldSendSMSLinkIOS() throws Exception { assertThat(callback, hasNoError()); } + @Test + public void shouldSendSMSLinkIOSSync() throws Throwable { + mockAPI.willReturnSuccessfulPasswordlessStart(); + + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_IOS) + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/passwordless/start")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("phone_number", "+1123123123")); + assertThat(body, hasEntry("send", "link_ios")); + assertThat(body, hasEntry("connection", "sms")); + } + private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); } diff --git a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java index 421b4d2a..22ba8258 100644 --- a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java +++ b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java @@ -69,6 +69,11 @@ public void setUp() throws Exception { MockitoAnnotations.initMocks(this); HttpUrl url = HttpUrl.parse("https://auth0.com"); baseRequest = new BaseRequest(url, client, reader, writer, callback) { + @Override + public String execute() throws Throwable { + return null; + } + @Override public void onResponse(Response response) throws IOException { From 65e17a3c97c7c1ca0820766f8031317035c70797 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Mon, 18 Jan 2016 10:05:05 -0300 Subject: [PATCH 31/89] Add Auth0Exception. Use Auth0Exception instead of Throwable Rename APIClientException -> APIException and use this class only for the server/api errors --- .../main/java/com/auth0/Auth0Exception.java | 39 ++++++++ .../authentication/AuthenticationRequest.java | 9 +- .../authentication/ChangePasswordRequest.java | 5 +- .../authentication/DelegationRequest.java | 5 +- .../auth0/authentication/SignUpRequest.java | 7 +- ...ClientException.java => APIException.java} | 10 +- .../com/auth0/authentication/api/Request.java | 5 +- .../api/RequestBodyBuildException.java | 4 +- .../authentication/api/callback/Callback.java | 6 +- .../api/internal/ApplicationInfoRequest.java | 46 ++++------ .../api/internal/BaseRequest.java | 29 ++++-- .../api/internal/SimpleRequest.java | 63 ++++--------- .../api/internal/VoidRequest.java | 42 ++------- .../AuthenticationAPIClientTest.java | 92 +++++++++---------- .../api/internal/BaseRequestTest.java | 9 +- .../api/util/MockBaseCallback.java | 11 ++- 16 files changed, 197 insertions(+), 185 deletions(-) create mode 100644 core/src/main/java/com/auth0/Auth0Exception.java rename core/src/main/java/com/auth0/authentication/api/{APIClientException.java => APIException.java} (88%) diff --git a/core/src/main/java/com/auth0/Auth0Exception.java b/core/src/main/java/com/auth0/Auth0Exception.java new file mode 100644 index 00000000..57eb9e1d --- /dev/null +++ b/core/src/main/java/com/auth0/Auth0Exception.java @@ -0,0 +1,39 @@ +/* + * Auth0Exception.java + * + * Copyright (c) 2016 Auth0 (http://auth0.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.auth0; + +/** + * All exceptions from Auth0 + */ +public class Auth0Exception extends RuntimeException { + + public Auth0Exception(String message, Throwable cause) { + super(message, cause); + } + + public Auth0Exception(String message) { + super(message); + } +} diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index 3b331d19..1f4c37a1 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -24,6 +24,7 @@ package com.auth0.authentication; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.ParameterBuilder; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.Request; @@ -98,14 +99,14 @@ public void onSuccess(UserProfile profile) { } @Override - public void onFailure(Throwable error) { + public void onFailure(Auth0Exception error) { callback.onFailure(error); } }); } @Override - public void onFailure(Throwable error) { + public void onFailure(Auth0Exception error) { callback.onFailure(error); } }); @@ -114,10 +115,10 @@ public void onFailure(Throwable error) { /** * Executes the log in request and then fetches the user's profile * @return authentication object on success - * @throws Throwable on failure + * @throws Auth0Exception on failure */ @Override - public Authentication execute() throws Throwable { + public Authentication execute() throws Auth0Exception { Token token = credentialsRequest.execute(); Map parameters = new ParameterBuilder() .clearAll() diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index c918ba91..dc1b6f81 100644 --- a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -24,6 +24,7 @@ package com.auth0.authentication; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.callback.BaseCallback; @@ -93,10 +94,10 @@ public void start(final BaseCallback callback) { /** * Executes the HTTP request against Auth0 API * @return Void on success - * @throws Throwable on failure + * @throws Auth0Exception on failure */ @Override - public Void execute() throws Throwable { + public Void execute() throws Auth0Exception { return request.execute(); } } diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index a95e5f25..201ca6ff 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -24,6 +24,7 @@ package com.auth0.authentication; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.ParameterBuilder; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.Request; @@ -103,10 +104,10 @@ public void start(final BaseCallback callback) { /** * Executes the HTTP request against Auth0 API * @return the delegation response on success - * @throws Throwable on failure + * @throws Auth0Exception on failure */ @Override - public T execute() throws Throwable { + public T execute() throws Auth0Exception { return request.execute(); } } diff --git a/core/src/main/java/com/auth0/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/authentication/SignUpRequest.java index c7d81d19..15fc7999 100644 --- a/core/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -24,6 +24,7 @@ package com.auth0.authentication; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.Request; import com.auth0.authentication.api.callback.BaseCallback; @@ -98,7 +99,7 @@ public void onSuccess(final DatabaseUser user) { } @Override - public void onFailure(Throwable error) { + public void onFailure(Auth0Exception error) { callback.onFailure(error); } }); @@ -107,10 +108,10 @@ public void onFailure(Throwable error) { /** * Execute the create user request and then logs the user in. * @return authentication object on success - * @throws Throwable on failure + * @throws Auth0Exception on failure */ @Override - public Authentication execute() throws Throwable { + public Authentication execute() throws Auth0Exception { signUpRequest.execute(); return authenticationRequest.execute(); } diff --git a/core/src/main/java/com/auth0/authentication/api/APIClientException.java b/core/src/main/java/com/auth0/authentication/api/APIException.java similarity index 88% rename from core/src/main/java/com/auth0/authentication/api/APIClientException.java rename to core/src/main/java/com/auth0/authentication/api/APIException.java index 20c51249..5c044976 100644 --- a/core/src/main/java/com/auth0/authentication/api/APIClientException.java +++ b/core/src/main/java/com/auth0/authentication/api/APIException.java @@ -24,13 +24,15 @@ package com.auth0.authentication.api; +import com.auth0.Auth0Exception; + import java.util.HashMap; import java.util.Map; /** * Internal exception raised when a request to the API fails */ -public class APIClientException extends RuntimeException { +public class APIException extends Auth0Exception { private int statusCode; @@ -41,7 +43,7 @@ public class APIClientException extends RuntimeException { * @param detailMessage error message * @param throwable the cause of the exception */ - public APIClientException(String detailMessage, Throwable throwable) { + public APIException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); this.statusCode = -1; this.responseError = new HashMap<>(); @@ -53,7 +55,7 @@ public APIClientException(String detailMessage, Throwable throwable) { * @param statusCode status code returned by the server * @param responseError payload of the error returned by the server */ - public APIClientException(String detailMessage, int statusCode, Map responseError) { + public APIException(String detailMessage, int statusCode, Map responseError) { super(detailMessage); this.statusCode = statusCode; this.responseError = responseError != null ? responseError : new HashMap(); @@ -66,7 +68,7 @@ public APIClientException(String detailMessage, int statusCode, Map responseError) { + public APIException(String detailMessage, Throwable throwable, int statusCode, Map responseError) { super(detailMessage, throwable); this.statusCode = statusCode; this.responseError = responseError != null ? responseError : new HashMap(); diff --git a/core/src/main/java/com/auth0/authentication/api/Request.java b/core/src/main/java/com/auth0/authentication/api/Request.java index 8d1d72e0..c0338750 100644 --- a/core/src/main/java/com/auth0/authentication/api/Request.java +++ b/core/src/main/java/com/auth0/authentication/api/Request.java @@ -24,6 +24,7 @@ package com.auth0.authentication.api; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.callback.BaseCallback; /** @@ -41,7 +42,7 @@ public interface Request { /** * Executes the HTTP request against Auth0 API (blocking the current thread) * @return the response on success - * @throws Throwable on failure + * @throws Auth0Exception on failure */ - T execute() throws Throwable; + T execute() throws Auth0Exception; } diff --git a/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java index 2f31e81a..10b1e611 100644 --- a/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java +++ b/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java @@ -24,10 +24,12 @@ package com.auth0.authentication.api; +import com.auth0.Auth0Exception; + /** * Exception that wraps errors when creating a body for a request */ -public class RequestBodyBuildException extends RuntimeException { +public class RequestBodyBuildException extends Auth0Exception { public RequestBodyBuildException(String message, Throwable cause) { super(message, cause); diff --git a/core/src/main/java/com/auth0/authentication/api/callback/Callback.java b/core/src/main/java/com/auth0/authentication/api/callback/Callback.java index 8b746f05..48e3ec6c 100644 --- a/core/src/main/java/com/auth0/authentication/api/callback/Callback.java +++ b/core/src/main/java/com/auth0/authentication/api/callback/Callback.java @@ -24,6 +24,8 @@ package com.auth0.authentication.api.callback; +import com.auth0.Auth0Exception; + /** * Interface for all callbacks used with Auth0 API clients */ @@ -31,8 +33,8 @@ public interface Callback { /** * Method called on Auth0 API request failure - * @param error Error with the reason of the failure + * @param error Auth0Exception with the reason of the failure */ - void onFailure(Throwable error); + void onFailure(Auth0Exception error); } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index 81f02c67..381280ad 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -25,9 +25,10 @@ package com.auth0.authentication.api.internal; import com.auth0.Application; -import com.auth0.authentication.api.APIClientException; +import com.auth0.Auth0Exception; +import com.auth0.authentication.api.APIException; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.RequestBodyBuildException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; @@ -44,7 +45,7 @@ class ApplicationInfoRequest extends BaseRequest implements Callback { public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper mapper) { - super(url, client, mapper.reader(Application.class), null); + super(url, client, mapper.reader(Application.class), mapper.reader(new TypeReference>() {}), null); } @Override @@ -53,24 +54,19 @@ protected Request doBuildRequest(Request.Builder builder) { return request; } - @Override - public void onFailure(Request request, IOException e) { - postOnFailure(e); - } - @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { - String message = "Received app info failed response with code " + response.code() + " and body " + response.body().string(); - postOnFailure(new IOException(message)); + APIException exception = parseUnsuccessfulResponse(response); + postOnFailure(exception); return; } try { String json = response.body().string(); Application app = parseJSONP(json); postOnSuccess(app); - } catch (Throwable e) { - postOnFailure(e); + } catch (Exception e) { + postOnFailure(new Auth0Exception("Failed to parse response to request to " + url, e)); } } @@ -85,33 +81,31 @@ public ParameterizableRequest addHeader(String name, String value) } @Override - public Application execute() throws Throwable { - Request request; - try { - request = doBuildRequest(newBuilder()); - } catch (RequestBodyBuildException e) { - throw new APIClientException("Failed to send request to " + url.toString(), e); - } + public Application execute() throws Auth0Exception { + Request request = doBuildRequest(newBuilder()); Response response; try { response = client.newCall(request).execute(); } catch (IOException e) { - throw new APIClientException("Failed to execute request to " + url.toString(), e); + throw new Auth0Exception("Failed to execute request to " + url, e); } if (!response.isSuccessful()) { - String message = "Received app info failed response with code " + response.code() + " and body " + response.body().string(); - throw new IOException(message); + throw parseUnsuccessfulResponse(response); } - String json = response.body().string(); - return parseJSONP(json); + try { + String json = response.body().string(); + return parseJSONP(json); + } catch (Exception e) { + throw new Auth0Exception("Failed to parse response to request to " + url, e); + } } - private Application parseJSONP(String json) throws Throwable { + private Application parseJSONP(String json) throws Exception { if (json.length() < 16) { - throw new JSONException("Failed to parse JSONP"); + throw new JSONException("Invalid App Info JSONP"); } json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method JSONTokener tokenizer = new JSONTokener(json); diff --git a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java index 3379a907..aceed88a 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java @@ -24,7 +24,8 @@ package com.auth0.authentication.api.internal; -import com.auth0.authentication.api.APIClientException; +import com.auth0.Auth0Exception; +import com.auth0.authentication.api.APIException; import com.auth0.authentication.api.AuthorizableRequest; import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.RequestBodyBuildException; @@ -36,8 +37,10 @@ import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; import java.io.IOException; +import java.io.InputStream; import java.util.HashMap; import java.util.Map; @@ -48,18 +51,20 @@ abstract class BaseRequest implements ParameterizableRequest, Authorizable protected final HttpUrl url; protected final OkHttpClient client; private final ObjectReader reader; + private final ObjectReader errorReader; private final ObjectWriter writer; private BaseCallback callback; - protected BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer) { - this(url, client, reader, writer, null); + protected BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectReader errorReader, ObjectWriter writer) { + this(url, client, reader, errorReader, writer, null); } - public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectWriter writer, BaseCallback callback) { + public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, ObjectReader errorReader, ObjectWriter writer, BaseCallback callback) { this.url = url; this.client = client; this.reader = reader; + this.errorReader = errorReader; this.writer = writer; this.callback = callback; this.headers = new HashMap<>(); @@ -74,7 +79,7 @@ protected void postOnSuccess(final T payload) { this.callback.onSuccess(payload); } - protected final void postOnFailure(final Throwable error) { + protected final void postOnFailure(final Auth0Exception error) { this.callback.onFailure(error); } @@ -99,6 +104,16 @@ protected RequestBody buildBody() throws RequestBodyBuildException { return JsonRequestBodyBuilder.createBody(parameters, writer); } + protected APIException parseUnsuccessfulResponse(Response response) { + try { + final InputStream byteStream = response.body().byteStream(); + Map payload = errorReader.readValue(byteStream); + return new APIException("Request to " + url + " failed with response " + payload, response.code(), payload); + } catch (Exception e) { + return new APIException("Request to " + url + " failed", response.code(), null); + } + } + private static abstract class CallbackTask implements Runnable { protected final BaseCallback callback; @@ -109,7 +124,7 @@ protected CallbackTask(BaseCallback callback) { @Override public void onFailure(Request request, IOException e) { - postOnFailure(e); + postOnFailure(new Auth0Exception("Failed to execute request to " + url.toString(), e)); } @Override @@ -139,7 +154,7 @@ public void start(BaseCallback callback) { Request request = doBuildRequest(newBuilder()); client.newCall(request).enqueue(this); } catch (RequestBodyBuildException e) { - callback.onFailure(new APIClientException("Failed to send request to " + url.toString(), e)); + callback.onFailure(e); } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java index 852a3a2b..9b69fb78 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java @@ -24,16 +24,16 @@ package com.auth0.authentication.api.internal; -import com.auth0.authentication.api.APIClientException; +import com.auth0.Auth0Exception; +import com.auth0.authentication.api.APIException; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; @@ -41,49 +41,39 @@ import java.io.InputStream; import java.util.Map; -class SimpleRequest extends BaseRequest implements Request, ParameterizableRequest, Callback { +class SimpleRequest extends BaseRequest implements ParameterizableRequest, Callback { - private final ObjectReader errorReader; private final String method; public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { - super(url, client, mapper.reader(clazz), mapper.writer()); - this.errorReader = mapper.reader(new TypeReference>() {}); + super(url, client, mapper.reader(clazz), mapper.reader(new TypeReference>() {}), mapper.writer()); this.method = httpMethod; } public SimpleRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { - super(url, client, mapper.reader(new TypeReference>() {}), mapper.writer()); - this.errorReader = mapper.reader(new TypeReference>() { - }); + super(url, client, mapper.reader(new TypeReference>() {}), mapper.reader(new TypeReference>() {}), mapper.writer()); this.method = httpMethod; } @Override public void onResponse(Response response) throws IOException { - final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { - Throwable throwable; - try { - Map payload = errorReader.readValue(byteStream); - throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); - } catch (IOException e) { - throwable = new APIClientException("Request failed", response.code(), null); - } - postOnFailure(throwable); + APIException exception = parseUnsuccessfulResponse(response); + postOnFailure(exception); return; } try { + final InputStream byteStream = response.body().byteStream(); T payload = getReader().readValue(byteStream); postOnSuccess(payload); - } catch (IOException e) { - postOnFailure(new APIClientException("Request failed", response.code(), null)); + } catch (Exception e) { + postOnFailure(new Auth0Exception("Failed to parse response to request to " + url, e)); } } @Override - protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request.Builder builder) throws RequestBodyBuildException { + protected Request doBuildRequest(Request.Builder builder) throws RequestBodyBuildException { RequestBody body = buildBody(); return newBuilder() .method(method, body) @@ -91,38 +81,25 @@ protected com.squareup.okhttp.Request doBuildRequest(com.squareup.okhttp.Request } @Override - public T execute() throws Throwable { - com.squareup.okhttp.Request request; - try { - request = doBuildRequest(newBuilder()); - } catch (RequestBodyBuildException e) { - throw new APIClientException("Failed to send request to " + url.toString(), e); - } + public T execute() throws Auth0Exception { + Request request = doBuildRequest(newBuilder()); Response response; try { response = client.newCall(request).execute(); } catch (IOException e) { - throw new APIClientException("Failed to execute request to " + url.toString(), e); + throw new Auth0Exception("Failed to execute request to " + url, e); } - final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { - Throwable throwable; - try { - Map payload = errorReader.readValue(byteStream); - throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); - } catch (IOException e) { - throwable = new APIClientException("Request failed", response.code(), null); - } - throw throwable; + throw parseUnsuccessfulResponse(response); } try { - T payload = getReader().readValue(byteStream); - return payload; - } catch (IOException e) { - throw new APIClientException("Request failed", response.code(), null); + final InputStream byteStream = response.body().byteStream(); + return getReader().readValue(byteStream); + } catch (Exception e) { + throw new Auth0Exception("Failed to parse response to request to " + url, e); } } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java index bbbc66f5..88f644af 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java @@ -24,11 +24,11 @@ package com.auth0.authentication.api.internal; -import com.auth0.authentication.api.APIClientException; +import com.auth0.Auth0Exception; +import com.auth0.authentication.api.APIException; import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; import com.squareup.okhttp.Callback; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -37,33 +37,22 @@ import com.squareup.okhttp.Response; import java.io.IOException; -import java.io.InputStream; import java.util.Map; class VoidRequest extends BaseRequest implements Callback { - private final ObjectReader errorReader; private final String httpMethod; public VoidRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { - super(url, client, null, mapper.writer()); + super(url, client, null, mapper.reader(new TypeReference>() {}), mapper.writer()); this.httpMethod = httpMethod; - this.errorReader = mapper.reader(new TypeReference>() { - }); } @Override public void onResponse(Response response) throws IOException { - final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { - Throwable throwable; - try { - Map payload = errorReader.readValue(byteStream); - throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); - } catch (IOException e) { - throwable = new APIClientException("Request failed", response.code(), null); - } - postOnFailure(throwable); + APIException exception = parseUnsuccessfulResponse(response); + postOnFailure(exception); return; } @@ -79,31 +68,18 @@ protected Request doBuildRequest(Request.Builder builder) { } @Override - public Void execute() throws Throwable { - Request request; - try { - request = doBuildRequest(newBuilder()); - } catch (RequestBodyBuildException e) { - throw new APIClientException("Failed to send request to " + url.toString(), e); - } + public Void execute() throws Auth0Exception { + Request request = doBuildRequest(newBuilder()); Response response; try { response = client.newCall(request).execute(); } catch (IOException e) { - throw new APIClientException("Failed to execute request to " + url.toString(), e); + throw new Auth0Exception("Failed to execute request to " + url.toString(), e); } - final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { - Throwable throwable; - try { - Map payload = errorReader.readValue(byteStream); - throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); - } catch (IOException e) { - throwable = new APIClientException("Request failed", response.code(), null); - } - throw throwable; + throw parseUnsuccessfulResponse(response); } return null; } diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index c1bb064f..6be1e7af 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -25,12 +25,8 @@ package com.auth0.authentication; +import com.auth0.*; import com.auth0.authentication.api.ParameterBuilder; -import com.auth0.Application; -import com.auth0.Auth0; -import com.auth0.DatabaseUser; -import com.auth0.Token; -import com.auth0.UserProfile; import com.auth0.authentication.api.util.AuthenticationAPI; import com.auth0.authentication.api.util.MockBaseCallback; import com.fasterxml.jackson.core.type.TypeReference; @@ -98,7 +94,7 @@ public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { } @Test - public void shouldLoadApplicationInfoFromConfigurationUrlSync() throws Throwable { + public void shouldLoadApplicationInfoFromConfigurationUrlSync() throws Exception { mockAPI.willReturnValidApplicationResponse(); final Application application = client @@ -122,16 +118,16 @@ public void shoulFailWithInvalidJSON() throws Exception { public void shoulFailWithInvalidJSONSync() throws Exception { mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); - Throwable throwable = null; + Exception exception = null; try { client .fetchApplicationInfo() .execute(); - } catch (Throwable e) { - throwable = e; + } catch (Auth0Exception e) { + exception = e; } - assertThat(throwable, is(notNullValue())); + assertThat(exception, is(notNullValue())); } @Test @@ -147,16 +143,16 @@ public void shoulFailWithInvalidJSONP() throws Exception { public void shoulFailWithInvalidJSONPSync() throws Exception { mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); - Throwable throwable = null; + Exception exception = null; try { client .fetchApplicationInfo() .execute(); - } catch (Throwable e) { - throwable = e; + } catch (Auth0Exception e) { + exception = e; } - assertThat(throwable, is(notNullValue())); + assertThat(exception, is(notNullValue())); } @Test @@ -174,16 +170,16 @@ public void shouldFailWithFailedStatusCode() throws Exception { public void shouldFailWithFailedStatusCodeSync() throws Exception { mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); - Throwable throwable = null; + Exception exception = null; try { client .fetchApplicationInfo() .execute(); - } catch (Throwable e) { - throwable = e; + } catch (Auth0Exception e) { + exception = e; } - assertThat(throwable, is(notNullValue())); + assertThat(exception, is(notNullValue())); } @Test @@ -216,7 +212,7 @@ public void shouldLoginWithResourceOwner() throws Exception { } @Test - public void shouldLoginWithResourceOwnerSync() throws Throwable { + public void shouldLoginWithResourceOwnerSync() throws Exception { mockAPI.willReturnSuccessfulLogin(); final Map parameters = ParameterBuilder.newBuilder() @@ -275,16 +271,16 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { .set("password", "notapassword") .asDictionary(); - Throwable throwable = null; + Exception exception = null; try { client.loginWithResourceOwner() .addParameters(parameters) .execute(); - } catch (Throwable e) { - throwable = e; + } catch (Auth0Exception e) { + exception = e; } - assertThat(throwable, is(notNullValue())); + assertThat(exception, is(notNullValue())); } @Test @@ -301,7 +297,7 @@ public void shouldLoginWithUserAndPassword() throws Exception { } @Test - public void shouldLoginWithUserAndPasswordSync() throws Throwable { + public void shouldLoginWithUserAndPasswordSync() throws Exception { mockAPI .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -328,7 +324,7 @@ public void shouldFetchTokenInfo() throws Exception { } @Test - public void shouldFetchTokenInfoSync() throws Throwable { + public void shouldFetchTokenInfoSync() throws Exception { mockAPI.willReturnTokenInfo(); final UserProfile profile = client @@ -363,7 +359,7 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { } @Test - public void shouldLoginWithOAuthAccessTokenSync() throws Throwable { + public void shouldLoginWithOAuthAccessTokenSync() throws Exception { mockAPI .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -406,7 +402,7 @@ public void shouldLoginWithPhoneNumber() throws Exception { } @Test - public void shouldLoginWithPhoneNumberSync() throws Throwable { + public void shouldLoginWithPhoneNumberSync() throws Exception { mockAPI .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -450,7 +446,7 @@ public void shouldLoginWithEmailOnly() throws Exception { } @Test - public void shouldLoginWithEmailOnlySync() throws Throwable { + public void shouldLoginWithEmailOnlySync() throws Exception { mockAPI .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -491,7 +487,7 @@ public void shouldCreateUser() throws Exception { } @Test - public void shouldCreateUserSync() throws Throwable { + public void shouldCreateUserSync() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final DatabaseUser user = client @@ -529,7 +525,7 @@ public void shouldCreateUserWithoutUsername() throws Exception { } @Test - public void shouldCreateUserWithoutUsernameSync() throws Throwable { + public void shouldCreateUserWithoutUsernameSync() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final DatabaseUser user = client @@ -569,7 +565,7 @@ public void shouldSignUpUser() throws Exception { } @Test - public void shouldSignUpUserSync() throws Throwable { + public void shouldSignUpUserSync() throws Exception { mockAPI.willReturnSuccessfulSignUp() .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -611,7 +607,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { } @Test - public void shouldSignUpUserWithoutUsernameSync() throws Throwable { + public void shouldSignUpUserWithoutUsernameSync() throws Exception { mockAPI.willReturnSuccessfulSignUp() .willReturnSuccessfulLogin() .willReturnTokenInfo(); @@ -652,7 +648,7 @@ public void shouldChangePassword() throws Exception { } @Test - public void shouldChangePasswordSync() throws Throwable { + public void shouldChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); client.changePassword("support@auth0.com") @@ -688,7 +684,7 @@ public void shouldRequestChangePassword() throws Exception { } @Test - public void shouldRequestChangePasswordSync() throws Throwable { + public void shouldRequestChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); client.changePassword("support@auth0.com") @@ -724,7 +720,7 @@ public void shouldCallDelegation() throws Exception { } @Test - public void shouldCallDelegationSync() throws Throwable { + public void shouldCallDelegationSync() throws Exception { mockAPI.willReturnGenericDelegationToken(); final Map response = client @@ -764,7 +760,7 @@ public void shouldGetNewIdTokenWithIdToken() throws Exception { } @Test - public void shouldGetNewIdTokenWithIdTokenSync() throws Throwable { + public void shouldGetNewIdTokenWithIdTokenSync() throws Exception { mockAPI.willReturnNewIdToken(); final Delegation delegation = client @@ -804,7 +800,7 @@ public void shouldGetNewIdTokenWithRefreshToken() throws Exception { } @Test - public void shouldGetNewIdTokenWithRefreshTokenSync() throws Throwable { + public void shouldGetNewIdTokenWithRefreshTokenSync() throws Exception { mockAPI.willReturnNewIdToken(); final Delegation delegation = client @@ -846,7 +842,7 @@ public void shouldGetCustomizedDelegationRequest() throws Exception { } @Test - public void shouldGetCustomizedDelegationRequestSync() throws Throwable { + public void shouldGetCustomizedDelegationRequestSync() throws Exception { mockAPI.willReturnNewIdToken(); client @@ -887,7 +883,7 @@ public void shouldUnlinkAccount() throws Exception { } @Test - public void shouldUnlinkAccountSync() throws Throwable { + public void shouldUnlinkAccountSync() throws Exception { mockAPI.willReturnSuccessfulUnlinkAccount(); client.unlink("user id", "access token") @@ -930,7 +926,7 @@ public void shouldStartPasswordless() throws Exception { } @Test - public void shouldStartPasswordlessSync() throws Throwable { + public void shouldStartPasswordlessSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final Map parameters = new ParameterBuilder() @@ -975,7 +971,7 @@ public void shouldSendEmailCode() throws Exception { } @Test - public void shouldSendEmailCodeSync() throws Throwable { + public void shouldSendEmailCodeSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithEmail("support@auth0.com", PasswordlessType.CODE) @@ -1012,7 +1008,7 @@ public void shouldSendEmailLink() throws Exception { } @Test - public void shouldSendEmailLinkSync() throws Throwable { + public void shouldSendEmailLinkSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK) @@ -1049,7 +1045,7 @@ public void shouldSendEmailLinkAndroid() throws Exception { } @Test - public void shouldSendEmailLinkAndroidSync() throws Throwable { + public void shouldSendEmailLinkAndroidSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_ANDROID) @@ -1086,7 +1082,7 @@ public void shouldSendEmailLinkIOS() throws Exception { } @Test - public void shouldSendEmailLinkIOSSync() throws Throwable { + public void shouldSendEmailLinkIOSSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_IOS) @@ -1123,7 +1119,7 @@ public void shouldSendSMSCode() throws Exception { } @Test - public void shouldSendSMSCodeSync() throws Throwable { + public void shouldSendSMSCodeSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithSMS("+1123123123", PasswordlessType.CODE) @@ -1160,7 +1156,7 @@ public void shouldSendSMSLink() throws Exception { } @Test - public void shouldSendSMSLinkSync() throws Throwable { + public void shouldSendSMSLinkSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK) @@ -1197,7 +1193,7 @@ public void shouldSendSMSLinkAndroid() throws Exception { } @Test - public void shouldSendSMSLinkAndroidSync() throws Throwable { + public void shouldSendSMSLinkAndroidSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_ANDROID) @@ -1234,7 +1230,7 @@ public void shouldSendSMSLinkIOS() throws Exception { } @Test - public void shouldSendSMSLinkIOSSync() throws Throwable { + public void shouldSendSMSLinkIOSSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_IOS) diff --git a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java index 22ba8258..1e9c2c79 100644 --- a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java +++ b/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java @@ -25,6 +25,7 @@ package com.auth0.authentication.api.internal; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.RequestBodyBuildException; import com.auth0.authentication.api.callback.BaseCallback; import com.fasterxml.jackson.databind.ObjectReader; @@ -54,12 +55,14 @@ public class BaseRequestTest { @Mock private BaseCallback callback; @Mock - private Throwable throwable; + private Auth0Exception throwable; @Mock private OkHttpClient client; @Mock private ObjectReader reader; @Mock + private ObjectReader errorReader; + @Mock private ObjectWriter writer; @Captor private ArgumentCaptor captor; @@ -68,9 +71,9 @@ public class BaseRequestTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); HttpUrl url = HttpUrl.parse("https://auth0.com"); - baseRequest = new BaseRequest(url, client, reader, writer, callback) { + baseRequest = new BaseRequest(url, client, reader, errorReader, writer, callback) { @Override - public String execute() throws Throwable { + public String execute() throws Auth0Exception { return null; } diff --git a/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java b/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java index 7cebc16e..90f94fb9 100644 --- a/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java +++ b/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java @@ -24,6 +24,7 @@ package com.auth0.authentication.api.util; +import com.auth0.Auth0Exception; import com.auth0.authentication.api.callback.BaseCallback; import java.util.concurrent.Callable; @@ -31,7 +32,7 @@ public class MockBaseCallback implements BaseCallback { private T payload; - private Throwable error; + private Auth0Exception error; @Override public void onSuccess(T payload) { @@ -39,7 +40,7 @@ public void onSuccess(T payload) { } @Override - public void onFailure(Throwable error) { + public void onFailure(Auth0Exception error) { this.error = error; } @@ -52,10 +53,10 @@ public T call() throws Exception { }; } - public Callable error() { - return new Callable() { + public Callable error() { + return new Callable() { @Override - public Throwable call() throws Exception { + public Auth0Exception call() throws Exception { return error; } }; From d4b94fc4d98174a3d9fea6b6cc7601341f72e89d Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Tue, 19 Jan 2016 11:33:38 -0300 Subject: [PATCH 32/89] Keep these methods public to allow compatibility with all functionality in Lock.Android --- .../com/auth0/authentication/AuthenticationAPIClient.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 58ab3cd5..566f2987 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -406,7 +406,7 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass .addParameters(parameters); } - protected ParameterizableRequest> delegation() { + public ParameterizableRequest> delegation() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("delegation") .build(); @@ -432,7 +432,7 @@ protected ParameterizableRequest delegation(Class clazz) { .addParameters(parameters); } - protected ParameterizableRequest passwordless() { + public ParameterizableRequest passwordless() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("passwordless") .addPathSegment("start") @@ -447,7 +447,7 @@ protected ParameterizableRequest passwordless() { .addParameters(parameters); } - protected ParameterizableRequest loginWithResourceOwner() { + public ParameterizableRequest loginWithResourceOwner() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("oauth") .addPathSegment("ro") From cf3cefe532a46432054312914560079e160bf071 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 21 Jan 2016 10:10:21 -0300 Subject: [PATCH 33/89] Add/improve javadoc Refactor some code, only catch expected Exceptions, etc --- .../main/java/com/auth0/Auth0Exception.java | 2 +- .../AuthenticationAPIClient.java | 13 +++++ .../authentication/AuthenticationRequest.java | 6 +-- .../authentication/ChangePasswordRequest.java | 8 +-- .../authentication/DelegationRequest.java | 18 ++++--- .../api/internal/ApplicationInfoRequest.java | 51 +++++++++---------- .../api/internal/SimpleRequest.java | 4 +- .../api/internal/VoidRequest.java | 1 - 8 files changed, 57 insertions(+), 46 deletions(-) diff --git a/core/src/main/java/com/auth0/Auth0Exception.java b/core/src/main/java/com/auth0/Auth0Exception.java index 57eb9e1d..61b2836f 100644 --- a/core/src/main/java/com/auth0/Auth0Exception.java +++ b/core/src/main/java/com/auth0/Auth0Exception.java @@ -25,7 +25,7 @@ package com.auth0; /** - * All exceptions from Auth0 + * Base Exception for any error found during a request to Auth0's API */ public class Auth0Exception extends RuntimeException { diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 566f2987..db53534e 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -406,6 +406,11 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass .addParameters(parameters); } + /** + * Performs a custom delegation request that will + * yield a delegation token. + * @return a request to configure and start + */ public ParameterizableRequest> delegation() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("delegation") @@ -432,6 +437,10 @@ protected ParameterizableRequest delegation(Class clazz) { .addParameters(parameters); } + /** + * Start a custom passwordless flow + * @return a request to configure and start + */ public ParameterizableRequest passwordless() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("passwordless") @@ -447,6 +456,10 @@ public ParameterizableRequest passwordless() { .addParameters(parameters); } + /** + * Perform a custom login request against the resource owner endpoint + * @return a request to configure and start + */ public ParameterizableRequest loginWithResourceOwner() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("oauth") diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index 1f4c37a1..f0d00910 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -113,9 +113,9 @@ public void onFailure(Auth0Exception error) { } /** - * Executes the log in request and then fetches the user's profile - * @return authentication object on success - * @throws Auth0Exception on failure + * Logs in the user with Auth0 and fetches it's profile. + * @return authentication object containing the user's tokens and profile + * @throws Auth0Exception when either authentication or profile fetch fails */ @Override public Authentication execute() throws Auth0Exception { diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index dc1b6f81..58b3a07e 100644 --- a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -83,7 +83,7 @@ public ChangePasswordRequest addHeader(String name, String value) { } /** - * Performs the HTTP request against Auth0 API + * Starts the change password request * @param callback called either on success or failure */ @Override @@ -92,9 +92,9 @@ public void start(final BaseCallback callback) { } /** - * Executes the HTTP request against Auth0 API - * @return Void on success - * @throws Auth0Exception on failure + * Executes the change password request + * @return nothing on success + * @throws Auth0Exception when the change password request fails */ @Override public Void execute() throws Auth0Exception { diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index 201ca6ff..2ebc93da 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -34,7 +34,11 @@ import java.util.Map; /** - * Represent a delegation request for Auth0 tokens that will yield a new 'id_token' + * Represents a delegation request for Auth0 tokens that will yield a new delegation token. + * The delegation response depends on the 'api_type' parameter. + * @param type of object that will hold the delegation response. When requesting Auth0’s 'id_token' you can + * use {@link Delegation}, otherwise you’ll need to provide an object that can be created from the JSON + * payload or just use {@code Map} */ public class DelegationRequest implements Request { @@ -66,7 +70,7 @@ public DelegationRequest addParameters(Map parameters) { } /** - * Set the api_type parameter to be sent in the request + * Set the 'api_type' parameter to be sent in the request * @param apiType the delegation api type * @return itself */ @@ -75,7 +79,7 @@ public DelegationRequest setApiType(String apiType) { } /** - * Set the scope used to make the delegation + * Set the 'scope' used to make the delegation * @param scope value * @return itself */ @@ -84,7 +88,7 @@ public DelegationRequest setScope(String scope) { } /** - * Set the target parameter to be sent in the request + * Set the 'target' parameter to be sent in the request * @param target the delegation target * @return itself */ @@ -93,7 +97,7 @@ public DelegationRequest setTarget(String target) { } /** - * Performs the HTTP request against Auth0 API + * Starts the delegation request against Auth0 API * @param callback called either on success or failure */ @Override @@ -102,9 +106,9 @@ public void start(final BaseCallback callback) { } /** - * Executes the HTTP request against Auth0 API + * Executes the delegation request against Auth0 API * @return the delegation response on success - * @throws Auth0Exception on failure + * @throws Auth0Exception when the delegation request fails */ @Override public T execute() throws Auth0Exception { diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index 381280ad..da3a4b99 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -50,8 +50,7 @@ public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper map @Override protected Request doBuildRequest(Request.Builder builder) { - final Request request = builder.build(); - return request; + return builder.build(); } @Override @@ -62,11 +61,10 @@ public void onResponse(Response response) throws IOException { return; } try { - String json = response.body().string(); - Application app = parseJSONP(json); + Application app = parseJSONP(response); postOnSuccess(app); - } catch (Exception e) { - postOnFailure(new Auth0Exception("Failed to parse response to request to " + url, e)); + } catch (Auth0Exception e) { + postOnFailure(e); } } @@ -83,41 +81,38 @@ public ParameterizableRequest addHeader(String name, String value) @Override public Application execute() throws Auth0Exception { Request request = doBuildRequest(newBuilder()); - Response response; try { response = client.newCall(request).execute(); } catch (IOException e) { throw new Auth0Exception("Failed to execute request to " + url, e); } - if (!response.isSuccessful()) { throw parseUnsuccessfulResponse(response); } + return parseJSONP(response); + } + private Application parseJSONP(Response response) { try { String json = response.body().string(); - return parseJSONP(json); - } catch (Exception e) { + if (json.length() < 16) { + throw new JSONException("Invalid App Info JSONP"); + } + json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method + JSONTokener tokenizer = new JSONTokener(json); + if (!tokenizer.more()) { + throw tokenizer.syntaxError("Invalid App Info JSONP"); + } + Object nextValue = tokenizer.nextValue(); + if (!(nextValue instanceof JSONObject)) { + tokenizer.back(); + throw tokenizer.syntaxError("Invalid JSON value of App Info"); + } + JSONObject jsonObject = (JSONObject) nextValue; + return getReader().readValue(jsonObject.toString()); + } catch (IOException | JSONException e) { throw new Auth0Exception("Failed to parse response to request to " + url, e); } } - - private Application parseJSONP(String json) throws Exception { - if (json.length() < 16) { - throw new JSONException("Invalid App Info JSONP"); - } - json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method - JSONTokener tokenizer = new JSONTokener(json); - if (!tokenizer.more()) { - throw tokenizer.syntaxError("Invalid App Info JSONP"); - } - Object nextValue = tokenizer.nextValue(); - if (!(nextValue instanceof JSONObject)) { - tokenizer.back(); - throw tokenizer.syntaxError("Invalid JSON value of App Info"); - } - JSONObject jsonObject = (JSONObject) nextValue; - return getReader().readValue(jsonObject.toString()); - } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java index 9b69fb78..a803d8c1 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java @@ -67,7 +67,7 @@ public void onResponse(Response response) throws IOException { final InputStream byteStream = response.body().byteStream(); T payload = getReader().readValue(byteStream); postOnSuccess(payload); - } catch (Exception e) { + } catch (IOException e) { postOnFailure(new Auth0Exception("Failed to parse response to request to " + url, e)); } } @@ -98,7 +98,7 @@ public T execute() throws Auth0Exception { try { final InputStream byteStream = response.body().byteStream(); return getReader().readValue(byteStream); - } catch (Exception e) { + } catch (IOException e) { throw new Auth0Exception("Failed to parse response to request to " + url, e); } } diff --git a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java index 88f644af..5a63c6a8 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java @@ -26,7 +26,6 @@ import com.auth0.Auth0Exception; import com.auth0.authentication.api.APIException; -import com.auth0.authentication.api.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; From 3873da29ef48ec7a93c28633b1da725707896eb4 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 21 Jan 2016 10:11:29 -0300 Subject: [PATCH 34/89] Add two more tests for delegation with id token --- .../AuthenticationAPIClientTest.java | 48 ++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 6be1e7af..c49a6b44 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -779,6 +779,50 @@ public void shouldGetNewIdTokenWithIdTokenSync() throws Exception { assertThat(delegation, is(notNullValue())); } + @Test + public void shouldGetCustomizedDelegationRequestWithIdToken() throws Exception { + mockAPI.willReturnNewIdToken(); + + final MockBaseCallback> callback = new MockBaseCallback<>(); + client.delegationWithIdToken(ID_TOKEN, "custom_api_type") + .setScope("custom_scope") + .setTarget("custom_target") + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "custom_api_type")); + assertThat(body, hasEntry("scope", "custom_scope")); + assertThat(body, hasEntry("target", "custom_target")); + assertThat(body, hasEntry("id_token", ID_TOKEN)); + } + + @Test + public void shouldGetCustomizedDelegationRequestWithIdTokenSync() throws Exception { + mockAPI.willReturnNewIdToken(); + + client + .delegationWithIdToken(ID_TOKEN, "custom_api_type") + .setScope("custom_scope") + .setTarget("custom_target") + .execute(); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/delegation")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("api_type", "custom_api_type")); + assertThat(body, hasEntry("scope", "custom_scope")); + assertThat(body, hasEntry("target", "custom_target")); + assertThat(body, hasEntry("id_token", ID_TOKEN)); + } + @Test public void shouldGetNewIdTokenWithRefreshToken() throws Exception { mockAPI.willReturnNewIdToken(); @@ -820,7 +864,7 @@ public void shouldGetNewIdTokenWithRefreshTokenSync() throws Exception { } @Test - public void shouldGetCustomizedDelegationRequest() throws Exception { + public void shouldGetCustomizedDelegationRequestWithRefreshToken() throws Exception { mockAPI.willReturnNewIdToken(); final MockBaseCallback> callback = new MockBaseCallback<>(); @@ -842,7 +886,7 @@ public void shouldGetCustomizedDelegationRequest() throws Exception { } @Test - public void shouldGetCustomizedDelegationRequestSync() throws Exception { + public void shouldGetCustomizedDelegationRequestWithRefreshTokenSync() throws Exception { mockAPI.willReturnNewIdToken(); client From 7021a91afe62f86db29006ea1e20a88005068121 Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 21 Jan 2016 10:26:39 -0300 Subject: [PATCH 35/89] Method is almost useless to the public It's only supposed to be used as an 'internal' help --- .../com/auth0/authentication/AuthenticationAPIClient.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index db53534e..19665e65 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -455,12 +455,8 @@ public ParameterizableRequest passwordless() { return RequestFactory.POST(url, client, mapper) .addParameters(parameters); } - - /** - * Perform a custom login request against the resource owner endpoint - * @return a request to configure and start - */ - public ParameterizableRequest loginWithResourceOwner() { + + protected ParameterizableRequest loginWithResourceOwner() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("oauth") .addPathSegment("ro") From c21bcb96ccfbc48cdd62bff3da257772477c13fb Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Thu, 21 Jan 2016 10:36:49 -0300 Subject: [PATCH 36/89] Change code to make it more clear that we're skipping the beginning of the JSONP What we need is the JSON that is used as parameter in the JSONP call --- .../authentication/api/internal/ApplicationInfoRequest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index da3a4b99..f213fe00 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -99,7 +99,7 @@ private Application parseJSONP(Response response) { if (json.length() < 16) { throw new JSONException("Invalid App Info JSONP"); } - json = json.substring(16); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method + json = json.substring("Auth0.setClient(".length()); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method JSONTokener tokenizer = new JSONTokener(json); if (!tokenizer.more()) { throw tokenizer.syntaxError("Invalid App Info JSONP"); From 782566b913619d5a21b30a9b3d11497a276bd140 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 22 Jan 2016 17:33:36 -0300 Subject: [PATCH 37/89] Extract to a constant --- .../api/internal/ApplicationInfoRequest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java index f213fe00..66a03187 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java @@ -44,6 +44,8 @@ class ApplicationInfoRequest extends BaseRequest implements Callback { + private static final String JSONP_PREFIX = "Auth0.setClient("; + public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper mapper) { super(url, client, mapper.reader(Application.class), mapper.reader(new TypeReference>() {}), null); } @@ -96,10 +98,11 @@ public Application execute() throws Auth0Exception { private Application parseJSONP(Response response) { try { String json = response.body().string(); - if (json.length() < 16) { + final int length = JSONP_PREFIX.length(); + if (json.length() < length) { throw new JSONException("Invalid App Info JSONP"); } - json = json.substring("Auth0.setClient(".length()); // replaces tokenizer.skipPast("Auth0.setClient(") because official (not android's) org.json does not have the method + json = json.substring(length); JSONTokener tokenizer = new JSONTokener(json); if (!tokenizer.more()) { throw tokenizer.syntaxError("Invalid App Info JSONP"); From 44dd814975f8599c9eb8e282816334718a3becce Mon Sep 17 00:00:00 2001 From: Nicolas Ulrich Date: Fri, 22 Jan 2016 18:04:29 -0300 Subject: [PATCH 38/89] Remove everything related to Application The request to obtain application info is only used by Lock Remove everything else related to Application: Connection, Strategy, Strategies, ApplicationInfoRequest, etc Remove tests The functionality will be added to Lock.Android v2 --- core/src/main/java/com/auth0/Application.java | 222 ------------------ core/src/main/java/com/auth0/Connection.java | 121 ---------- core/src/main/java/com/auth0/Strategies.java | 130 ---------- core/src/main/java/com/auth0/Strategy.java | 68 ------ .../AuthenticationAPIClient.java | 13 - .../api/internal/ApplicationInfoRequest.java | 121 ---------- .../api/internal/RequestFactory.java | 6 - .../test/java/com/auth0/ApplicationTest.java | 114 --------- .../test/java/com/auth0/ConnectionTest.java | 153 ------------ .../test/java/com/auth0/StrategiesTest.java | 45 ---- .../test/java/com/auth0/UserProfileTest.java | 3 - .../AuthenticationAPIClientTest.java | 101 -------- 12 files changed, 1097 deletions(-) delete mode 100644 core/src/main/java/com/auth0/Application.java delete mode 100644 core/src/main/java/com/auth0/Connection.java delete mode 100644 core/src/main/java/com/auth0/Strategies.java delete mode 100644 core/src/main/java/com/auth0/Strategy.java delete mode 100644 core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java delete mode 100644 core/src/test/java/com/auth0/ApplicationTest.java delete mode 100644 core/src/test/java/com/auth0/ConnectionTest.java delete mode 100644 core/src/test/java/com/auth0/StrategiesTest.java diff --git a/core/src/main/java/com/auth0/Application.java b/core/src/main/java/com/auth0/Application.java deleted file mode 100644 index 9c7327af..00000000 --- a/core/src/main/java/com/auth0/Application.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Application.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.List; - -import static com.auth0.authentication.api.util.CheckHelper.checkArgument; - -/** - * Class with your Auth0's application information and the list of enabled connections (DB, Social, Enterprise, Passwordless). - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Application { - - private String id; - private String tenant; - private String authorizeURL; - private String callbackURL; - private String subscription; - private boolean hasAllowedOrigins; - private List strategies; - private List socialStrategies; - private List enterpriseStrategies; - private Strategy databaseStrategy; - - public Application(Application application) { - id = application.id; - tenant = application.tenant; - authorizeURL = application.authorizeURL; - callbackURL = application.callbackURL; - subscription = application.subscription; - hasAllowedOrigins = application.hasAllowedOrigins; - strategies = application.strategies; - socialStrategies = application.socialStrategies; - enterpriseStrategies = application.enterpriseStrategies; - databaseStrategy = application.databaseStrategy; - } - - /** - * Creates a new application instance - * @param id app id. - * @param tenant name of the tenant who owns the app. - * @param authorizeURL url used to authorize during oauth flow. - * @param callbackURL url used after a oauth flow. - * @param subscription type of subscription. - * @param hasAllowedOrigins if the app allows other origins - * @param strategies list of the strategies enabled for the app (Social, DB, etc). - */ - @JsonCreator - public Application(@JsonProperty(value = "id") String id, - @JsonProperty(value = "tenant") String tenant, - @JsonProperty(value = "authorize") String authorizeURL, - @JsonProperty(value = "callback") String callbackURL, - @JsonProperty(value = "subscription") String subscription, - @JsonProperty(value = "hasAllowedOrigins") boolean hasAllowedOrigins, - @JsonProperty(value = "strategies") List strategies) { - checkArgument(id != null, "id must be non-null"); - checkArgument(tenant != null, "tenant must be non-null"); - checkArgument(authorizeURL != null, "authorize must be non-null"); - checkArgument(strategies != null && strategies.size() > 0, "Must have at least 1 strategy"); - this.id = id; - this.tenant = tenant; - this.authorizeURL = authorizeURL; - this.callbackURL = callbackURL; - this.subscription = subscription; - this.hasAllowedOrigins = hasAllowedOrigins; - this.strategies = strategies; - this.socialStrategies = new ArrayList<>(); - this.enterpriseStrategies = new ArrayList<>(); - for(Strategy strategy: strategies) { - if (Strategies.Auth0.getName().equals(strategy.getName())) { - this.databaseStrategy = strategy; - } else { - switch (strategy.getType()) { - case SOCIAL: - this.socialStrategies.add(strategy); - break; - case ENTERPRISE: - this.enterpriseStrategies.add(strategy); - break; - } - } - } - } - - /** - * Returns the id of the application. - * @return an ID - */ - public String getId() { - return id; - } - - /** - * Returns the name of the tenant who owns the app. - * @return name of the tenant - */ - public String getTenant() { - return tenant; - } - - /** - * Returns url used to authorize during oauth flow. - * @return a url string - */ - public String getAuthorizeURL() { - return authorizeURL; - } - - /** - * Returns url used after a oauth flow. - * @return a url string - */ - public String getCallbackURL() { - return callbackURL; - } - - /** - * Returns the type of subscription - * @return type of subscription - */ - public String getSubscription() { - return subscription; - } - - /** - * Returns if the app allows other origins. - * @return hasAllowedOrigins flag - */ - public boolean isHasAllowedOrigins() { - return hasAllowedOrigins; - } - - /** - * Returns all available auth strategies for the app. - * @return - */ - public List getStrategies() { - return new ArrayList<>(strategies); - } - - /** - * Returns the Database strategy of the app. - * @return DB strategy - */ - public Strategy getDatabaseStrategy() { - return databaseStrategy; - } - - /** - * Returns the social strategies of the app. - * @return list of social strategies - */ - public List getSocialStrategies() { - return new ArrayList<>(socialStrategies); - } - - /** - * Returns the social enterprise of the app. - * @return list of enterprise strategies - */ - public List getEnterpriseStrategies() { - return new ArrayList<>(enterpriseStrategies); - } - - /** - * Returns a {@link Strategy} by its name - * @param name strategy name - * @return a {@link Strategy} - */ - public Strategy strategyForName(String name) { - for (Strategy strategy: this.strategies) { - if (strategy.getName().equals(name)) { - return strategy; - } - } - return null; - } - - /** - * Returns the strategy by one of its connections - * @param connection a connection - * @return a {@link Strategy} - */ - public Strategy strategyForConnection(Connection connection) { - for (Strategy strategy : this.strategies) { - for (Connection conn : strategy.getConnections()) { - if (conn.getName().equals(connection.getName())) { - return strategy; - } - } - } - return null; - } -} diff --git a/core/src/main/java/com/auth0/Connection.java b/core/src/main/java/com/auth0/Connection.java deleted file mode 100644 index 4f9b6baf..00000000 --- a/core/src/main/java/com/auth0/Connection.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Connection.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.auth0.authentication.api.util.CheckHelper; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Class with a Auth0 connection info - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Connection { - - protected String name; - protected Map values; - - protected Connection(Connection connection) { - name = connection.name; - values = connection.values; - } - - protected Connection() { - - } - - /** - * Creates a new connection instance - * @param values Connection values - */ - @JsonCreator - public Connection(Map values) { - CheckHelper.checkArgument(values != null && values.size() > 0, "Must have at least one value"); - final String name = (String) values.remove("name"); - CheckHelper.checkArgument(name != null, "Must have a non-null name"); - this.name = name; - this.values = values; - } - - /** - * Returns all the connection values - * @return connection values - */ - public Map getValues() { - return values; - } - - public String getName() { - return name; - } - - /** - * Returns a value using its key - * @param key a key - * @param type of value to return - * @return a value - */ - @SuppressWarnings("unchecked") - public T getValueForKey(String key) { - return (T) this.values.get(key); - } - - /** - * Returns a boolean value using its key - * @param key a key - * @return the value of the flag - */ - public boolean booleanForKey(String key) { - Boolean value = getValueForKey(key); - if (value == null) { - return false; - } - return value; - } - - /** - * Get set of domain if the connection is Enterprise - * @return a set with all domains configured - */ - public Set getDomainSet() { - Set domains = new HashSet<>(); - String domain = getValueForKey("domain"); - if (domain != null) { - domains.add(domain.toLowerCase()); - List aliases = getValueForKey("domain_aliases"); - if (aliases != null) { - for (String alias: aliases) { - domains.add(alias.toLowerCase()); - } - } - } - return domains; - } -} diff --git a/core/src/main/java/com/auth0/Strategies.java b/core/src/main/java/com/auth0/Strategies.java deleted file mode 100644 index aa9aae2d..00000000 --- a/core/src/main/java/com/auth0/Strategies.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Strategies.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import static com.auth0.Strategies.Type.DATABASE; -import static com.auth0.Strategies.Type.ENTERPRISE; -import static com.auth0.Strategies.Type.PASSWORDLESS; -import static com.auth0.Strategies.Type.SOCIAL; - -/** - * An enum with all strategies available in Auth0 - */ -public enum Strategies { - Auth0("auth0", DATABASE), - - Email("email", PASSWORDLESS), - SMS("sms", PASSWORDLESS), - - Amazon("amazon", SOCIAL), - AOL("aol", SOCIAL), - Baidu("baidu", SOCIAL), - Box("box", SOCIAL), - Dwolla("dwolla", SOCIAL), - EBay("ebay", SOCIAL), - Evernote("evernote", SOCIAL), - EvernoteSandbox("evernote-sandbox", SOCIAL), - Exact("exact", SOCIAL), - Facebook("facebook", SOCIAL), - Fitbit("fitbit", SOCIAL), - Github("github", SOCIAL), - GooglePlus("google-oauth2", SOCIAL), - Instagram("instagram", SOCIAL), - Linkedin("linkedin", SOCIAL), - Miicard("miicard", SOCIAL), - Paypal("paypal", SOCIAL), - PlanningCenter("planningcenter", SOCIAL), - RenRen("renren", SOCIAL), - Salesforce("salesforce", SOCIAL), - SalesforceSandbox("salesforce-sandbox", SOCIAL), - Shopify("shopify", SOCIAL), - Soundcloud("soundcloud", SOCIAL), - TheCity("thecity", SOCIAL), - TheCitySandbox("thecity-sandbox", SOCIAL), - ThirtySevenSignals("thirtysevensignals", SOCIAL), - Twitter("twitter", SOCIAL), - VK("vkontakte", SOCIAL), - Weibo("weibo", SOCIAL), - WindowsLive("windowslive", SOCIAL), - Wordpress("wordpress", SOCIAL), - Yahoo("yahoo", SOCIAL), - Yammer("yammer", SOCIAL), - Yandex("yandex", SOCIAL), - - ActiveDirectory("ad", ENTERPRISE), - ADFS("adfs", ENTERPRISE), - Auth0LDAP("auth0-adldap", ENTERPRISE), - Custom("custom", ENTERPRISE), - GoogleApps("google-apps", ENTERPRISE), - GoogleOpenId("google-openid", ENTERPRISE), - IP("ip", ENTERPRISE), - MSCRM("mscrm", ENTERPRISE), - Office365("office365", ENTERPRISE), - PingFederate("pingfederate", ENTERPRISE), - SAMLP("samlp", ENTERPRISE), - Sharepoint("sharepoint", ENTERPRISE), - Waad("waad", ENTERPRISE), - - UnknownSocial("unknown-social", SOCIAL); - - private String name; - private Type type; - - Strategies(String name, Type type) { - this.name = name; - this.type = type; - } - - public String getName() { - return name; - } - - public Type getType() { - return type; - } - - public static Strategies fromName(String name) { - Strategies strategy = null; - for (Strategies str: values()) { - if (str.getName().equals(name)) { - strategy = str; - break; - } - } - - // if strategy not found, assume it's a new social type - if (strategy == null) - strategy = UnknownSocial; - - return strategy; - } - - public enum Type { - DATABASE, - SOCIAL, - ENTERPRISE, - PASSWORDLESS - } -} diff --git a/core/src/main/java/com/auth0/Strategy.java b/core/src/main/java/com/auth0/Strategy.java deleted file mode 100644 index 1fb92664..00000000 --- a/core/src/main/java/com/auth0/Strategy.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Strategy.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -/** - * Class with Auth0 authentication strategy info - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Strategy { - - private String name; - private List connections; - private Strategies strategyMetadata; - - @JsonCreator - public Strategy(@JsonProperty(value = "name", required = true) String name, - @JsonProperty(value = "connections", required = true) List connections) { - this.name = name; - this.connections = connections; - this.strategyMetadata = Strategies.fromName(name); - } - - public String getName() { - return name; - } - - public List getConnections() { - return connections; - } - - public Strategies.Type getType() { - return this.strategyMetadata.getType(); - } - - public boolean isResourceOwnerEnabled() { - return Strategies.ActiveDirectory.getName().equals(name) - || Strategies.ADFS.getName().equals(name) - || Strategies.Waad.getName().equals(name); - } -} diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 19665e65..524ebe97 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -28,7 +28,6 @@ import com.auth0.authentication.api.ParameterizableRequest; import com.auth0.authentication.api.Request; import com.auth0.authentication.api.internal.RequestFactory; -import com.auth0.Application; import com.auth0.Auth0; import com.auth0.DatabaseUser; import com.auth0.Token; @@ -103,18 +102,6 @@ public void setDefaultDbConnection(String defaultDbConnection) { this.defaultDbConnection = defaultDbConnection; } - /** - * Fetch application information from Auth0 - * @return a Auth0 request to start - */ - public Request fetchApplicationInfo() { - HttpUrl url = HttpUrl.parse(auth0.getConfigurationUrl()).newBuilder() - .addPathSegment("client") - .addPathSegment(auth0.getClientId() + ".js") - .build(); - return RequestFactory.newApplicationInfoRequest(url, client, mapper); - } - /** * Log in a user with email/username and password using a DB connection and fetch it's profile from Auth0 * @param usernameOrEmail of the user depending of the type of DB connection diff --git a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java b/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java deleted file mode 100644 index 66a03187..00000000 --- a/core/src/main/java/com/auth0/authentication/api/internal/ApplicationInfoRequest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * ApplicationInfoRequest.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.internal; - -import com.auth0.Application; -import com.auth0.Auth0Exception; -import com.auth0.authentication.api.APIException; -import com.auth0.authentication.api.ParameterizableRequest; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.squareup.okhttp.Callback; -import com.squareup.okhttp.HttpUrl; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONTokener; - -import java.io.IOException; -import java.util.Map; - -class ApplicationInfoRequest extends BaseRequest implements Callback { - - private static final String JSONP_PREFIX = "Auth0.setClient("; - - public ApplicationInfoRequest(OkHttpClient client, HttpUrl url, ObjectMapper mapper) { - super(url, client, mapper.reader(Application.class), mapper.reader(new TypeReference>() {}), null); - } - - @Override - protected Request doBuildRequest(Request.Builder builder) { - return builder.build(); - } - - @Override - public void onResponse(Response response) throws IOException { - if (!response.isSuccessful()) { - APIException exception = parseUnsuccessfulResponse(response); - postOnFailure(exception); - return; - } - try { - Application app = parseJSONP(response); - postOnSuccess(app); - } catch (Auth0Exception e) { - postOnFailure(e); - } - } - - @Override - public ParameterizableRequest addParameters(Map parameters) { - return this; - } - - @Override - public ParameterizableRequest addHeader(String name, String value) { - return this; - } - - @Override - public Application execute() throws Auth0Exception { - Request request = doBuildRequest(newBuilder()); - Response response; - try { - response = client.newCall(request).execute(); - } catch (IOException e) { - throw new Auth0Exception("Failed to execute request to " + url, e); - } - if (!response.isSuccessful()) { - throw parseUnsuccessfulResponse(response); - } - return parseJSONP(response); - } - - private Application parseJSONP(Response response) { - try { - String json = response.body().string(); - final int length = JSONP_PREFIX.length(); - if (json.length() < length) { - throw new JSONException("Invalid App Info JSONP"); - } - json = json.substring(length); - JSONTokener tokenizer = new JSONTokener(json); - if (!tokenizer.more()) { - throw tokenizer.syntaxError("Invalid App Info JSONP"); - } - Object nextValue = tokenizer.nextValue(); - if (!(nextValue instanceof JSONObject)) { - tokenizer.back(); - throw tokenizer.syntaxError("Invalid JSON value of App Info"); - } - JSONObject jsonObject = (JSONObject) nextValue; - return getReader().readValue(jsonObject.toString()); - } catch (IOException | JSONException e) { - throw new Auth0Exception("Failed to parse response to request to " + url, e); - } - } -} diff --git a/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java index 6c0d8457..5ca778c6 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java @@ -26,8 +26,6 @@ import com.auth0.authentication.api.AuthorizableRequest; import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; -import com.auth0.Application; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -85,10 +83,6 @@ public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient cli return addMetricHeader(new SimpleRequest<>(url, client, mapper, "DELETE", clazz)); } - public static Request newApplicationInfoRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { - return addMetricHeader(new ApplicationInfoRequest(client, url, mapper)); - } - private static ParameterizableRequest addMetricHeader(ParameterizableRequest request) { if (CLIENT_INFO != null) { request.addHeader("Auth0-Client", CLIENT_INFO); diff --git a/core/src/test/java/com/auth0/ApplicationTest.java b/core/src/test/java/com/auth0/ApplicationTest.java deleted file mode 100644 index 07dbe99e..00000000 --- a/core/src/test/java/com/auth0/ApplicationTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * ApplicationTest.java - * - * Copyright (c) 2016 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.auth0.Application; -import com.auth0.Connection; -import com.auth0.Strategies; -import com.auth0.Strategy; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static com.auth0.Strategies.ADFS; -import static com.auth0.Strategies.Auth0; -import static com.auth0.Strategies.Facebook; -import static com.auth0.Strategies.Office365; -import static com.auth0.Strategies.SAMLP; -import static com.auth0.Strategies.Twitter; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.*; - -public class ApplicationTest { - - public static final String ID = "ID"; - public static final String TENANT = "TENANT"; - public static final String AUTHORIZE_URL = "AUTHORIZE"; - public static final String CALLBACK_URL = "CALLBACK"; - public static final String SUBSCRIPTION = "SUBSCRIPTION"; - public static final boolean HAS_ALLOWED_ORIGINS = true; - - @Test - public void shouldInstantiateApplication() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application, is(notNullValue())); - } - - @Test - public void shouldHaveApplicationInfo() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application.getId(), equalTo(ID)); - assertThat(application.getTenant(), equalTo(TENANT)); - assertThat(application.getAuthorizeURL(), equalTo(AUTHORIZE_URL)); - assertThat(application.getCallbackURL(), equalTo(CALLBACK_URL)); - assertThat(application.getSubscription(), equalTo(SUBSCRIPTION)); - assertThat(application.isHasAllowedOrigins(), equalTo(HAS_ALLOWED_ORIGINS)); - } - - @Test - public void shouldReturnDatabaseStrategy() throws Exception { - Application application = newApplicationWithStrategies(Auth0); - assertThat(application.getDatabaseStrategy(), is(notNullValue())); - assertThat(application.getDatabaseStrategy().getName(), equalTo(Auth0.getName())); - } - - @Test - public void shouldReturnNoDatabaseStrategy() throws Exception { - Application application = newApplicationWithStrategies(Facebook); - assertThat(application.getDatabaseStrategy(), is(nullValue())); - } - - @Test - public void shouldReturnSocialStrategies() throws Exception { - Application application = newApplicationWithStrategies(Facebook, Twitter, Auth0); - assertThat(application.getSocialStrategies().size(), equalTo(2)); - } - - @Test - public void shouldReturnEnterpriseStrategies() throws Exception { - Application application = newApplicationWithStrategies(Auth0, ADFS, SAMLP, Office365); - assertThat(application.getEnterpriseStrategies().size(), equalTo(3)); - } - - private static Strategy newStrategyFor(Strategies strategyMetadata) { - return new Strategy(strategyMetadata.getName(), Arrays.asList(mock(Connection.class))); - } - - private static Application newApplicationWithStrategies(Strategies... list) { - List strategies = new ArrayList<>(); - for (Strategies str: list) { - strategies.add(newStrategyFor(str)); - } - Application application = new Application(ID, TENANT, AUTHORIZE_URL, CALLBACK_URL, SUBSCRIPTION, HAS_ALLOWED_ORIGINS, strategies); - return application; - } -} diff --git a/core/src/test/java/com/auth0/ConnectionTest.java b/core/src/test/java/com/auth0/ConnectionTest.java deleted file mode 100644 index 21c7b129..00000000 --- a/core/src/test/java/com/auth0/ConnectionTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * ConnectionTest.java - * - * Copyright (c) 2016 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.auth0.Connection; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -public class ConnectionTest { - - public static final String CONNECTION_NAME = "Username-Password"; - public static final Object VALUE = "value"; - public static final String KEY = "key"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void shouldBuildConnectionWithName() { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertNotNull(connection); - assertThat(connection.getName(), equalTo(CONNECTION_NAME)); - } - - @Test - public void shouldBuildConnectionWithValues() { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - assertThat(connection.getValues(), hasEntry(KEY, VALUE)); - } - - @Test - public void shouldNotStoreNameInValues() throws Exception { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertThat(connection.getValues(), not(hasKey("name"))); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldRaiseExceptionWhenNameIsNull() { - Map values = null; - new Connection(values); - } - - @Test - public void shouldReturnValueFromKey() { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - String value = connection.getValueForKey(KEY); - assertThat(value, equalTo(VALUE)); - } - - @Test - public void shouldReturnBooleanValueFromKey() { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put(KEY, true); - Connection connection = new Connection(values); - boolean value = connection.booleanForKey(KEY); - assertThat(value, is(true)); - } - - @Test - public void shouldReturnDefaultBooleanValueFromKey() { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - boolean value = connection.booleanForKey(KEY); - assertThat(value, is(false)); - } - - @Test - public void shouldRaiseExceptionWhenValueIsNotBoolean() { - expectedException.expect(ClassCastException.class); - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put(KEY, VALUE); - Connection connection = new Connection(values); - connection.booleanForKey(KEY); - } - - @Test - public void shouldReturnDomainNameInSet() throws Exception { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put("domain", "domain.com"); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet(), hasItem("domain.com")); - } - - @Test - public void shouldReturnAllDomainNamesAsSet() throws Exception { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - values.put("domain", "domain.com"); - values.put("domain_aliases", Arrays.asList("domain2.com", "domain3.com")); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet(), hasItems("domain.com", "domain2.com", "domain3.com")); - } - - @Test - public void shouldReturnEmptySetWithNoDomainName() throws Exception { - Map values = new HashMap<>(); - values.put("name", CONNECTION_NAME); - Connection connection = new Connection(values); - assertThat(connection.getDomainSet().isEmpty(), is(true)); - } -} diff --git a/core/src/test/java/com/auth0/StrategiesTest.java b/core/src/test/java/com/auth0/StrategiesTest.java deleted file mode 100644 index 82d6da5b..00000000 --- a/core/src/test/java/com/auth0/StrategiesTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * StrategiesTest.java - * - * Copyright (c) 2016 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0; - -import com.auth0.Strategies; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class StrategiesTest { - @Test - public void shouldReturnUnknownSocial() { - Strategies unknownSocial = Strategies.fromName("this-strategy-does-not-exist"); - assertEquals(unknownSocial.getType(), Strategies.Type.SOCIAL); - } - - @Test - public void shouldReturnValidDatabaseStrategy() { - Strategies auth0Database = Strategies.fromName("auth0"); - assertEquals(auth0Database.getType(), Strategies.Type.DATABASE); - } -} diff --git a/core/src/test/java/com/auth0/UserProfileTest.java b/core/src/test/java/com/auth0/UserProfileTest.java index 9c1f2b50..07af138d 100644 --- a/core/src/test/java/com/auth0/UserProfileTest.java +++ b/core/src/test/java/com/auth0/UserProfileTest.java @@ -25,9 +25,6 @@ package com.auth0; -import com.auth0.UserIdentity; -import com.auth0.UserProfile; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index c49a6b44..74947b7d 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -81,107 +81,6 @@ public void shouldCreateClientWithAccountInfo() throws Exception { assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); } - @Test - public void shouldLoadApplicationInfoFromConfigurationUrl() throws Exception { - mockAPI.willReturnValidApplicationResponse(); - - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - - assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); - assertThat(callback, hasPayloadOfType(Application.class)); - } - - @Test - public void shouldLoadApplicationInfoFromConfigurationUrlSync() throws Exception { - mockAPI.willReturnValidApplicationResponse(); - - final Application application = client - .fetchApplicationInfo() - .execute(); - - assertThat(mockAPI.takeRequest().getPath(), equalTo("/client/CLIENTID.js")); - assertThat(application, is(notNullValue())); - } - - @Test - public void shoulFailWithInvalidJSON() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shoulFailWithInvalidJSONSync() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Auth0Client.set({ })", 200); - - Exception exception = null; - try { - client - .fetchApplicationInfo() - .execute(); - } catch (Auth0Exception e) { - exception = e; - } - - assertThat(exception, is(notNullValue())); - } - - @Test - public void shoulFailWithInvalidJSONP() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); - final MockBaseCallback callback = new MockBaseCallback<>(); - client.fetchApplicationInfo() - .start(callback); - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shoulFailWithInvalidJSONPSync() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("INVALID_JSONP", 200); - - Exception exception = null; - try { - client - .fetchApplicationInfo() - .execute(); - } catch (Auth0Exception e) { - exception = e; - } - - assertThat(exception, is(notNullValue())); - } - - @Test - public void shouldFailWithFailedStatusCode() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); - final MockBaseCallback callback = new MockBaseCallback<>(); - - client.fetchApplicationInfo() - .start(callback); - - assertThat(callback, hasNoPayloadOfType(Application.class)); - } - - @Test - public void shouldFailWithFailedStatusCodeSync() throws Exception { - mockAPI.willReturnApplicationResponseWithBody("Not Found", 404); - - Exception exception = null; - try { - client - .fetchApplicationInfo() - .execute(); - } catch (Auth0Exception e) { - exception = e; - } - - assertThat(exception, is(notNullValue())); - } - @Test public void shouldLoginWithResourceOwner() throws Exception { mockAPI.willReturnSuccessfulLogin(); From 007dea88009f877832d734ce650f317ea34c6a03 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 22 Jan 2016 19:48:27 -0300 Subject: [PATCH 39/89] Moved classes around plus some cleanup --- .../api => }/APIException.java | 4 +- .../api => }/RequestBodyBuildException.java | 2 +- .../AuthenticationAPIClient.java | 16 +++---- .../authentication/AuthenticationRequest.java | 12 +++--- .../authentication/ChangePasswordRequest.java | 4 +- .../authentication/DelegationRequest.java | 8 ++-- .../{api => }/ParameterBuilder.java | 5 +-- .../auth0/authentication/SignUpRequest.java | 9 ++-- .../api/callback/AuthenticationCallback.java | 43 ------------------- .../api/callback/RefreshIdTokenCallback.java | 39 ----------------- .../{ => result}/Authentication.java | 7 +-- .../result}/DatabaseUser.java | 2 +- .../{ => result}/Delegation.java | 4 +- .../{ => authentication/result}/Token.java | 2 +- .../result}/UserIdentity.java | 2 +- .../result}/UserProfile.java | 4 +- .../api => }/callback/BaseCallback.java | 2 +- .../api => }/callback/Callback.java | 2 +- .../api => }/internal/BaseRequest.java | 12 +++--- .../internal/JsonRequestBodyBuilder.java | 4 +- .../api => }/internal/RequestFactory.java | 6 +-- .../api => }/internal/SimpleRequest.java | 8 ++-- .../api => }/internal/VoidRequest.java | 4 +- .../api => request}/AuthorizableRequest.java | 2 +- .../ParameterizableRequest.java | 2 +- .../api => request}/Request.java | 4 +- .../api => }/util/CheckHelper.java | 2 +- .../test/java/com/auth0/UserProfileTest.java | 3 ++ .../AuthenticationAPIClientTest.java | 24 ++++++----- .../{api => }/ParameterBuilderTest.java | 2 +- .../api => }/internal/BaseRequestTest.java | 6 +-- .../api => }/util/AuthenticationAPI.java | 2 +- .../api => }/util/CallbackMatcher.java | 2 +- .../api => }/util/MockBaseCallback.java | 4 +- 34 files changed, 87 insertions(+), 167 deletions(-) rename core/src/main/java/com/auth0/{authentication/api => }/APIException.java (97%) rename core/src/main/java/com/auth0/{authentication/api => }/RequestBodyBuildException.java (97%) rename core/src/main/java/com/auth0/authentication/{api => }/ParameterBuilder.java (97%) delete mode 100644 core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java delete mode 100644 core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java rename core/src/main/java/com/auth0/authentication/{ => result}/Authentication.java (91%) rename core/src/main/java/com/auth0/{ => authentication/result}/DatabaseUser.java (98%) rename core/src/main/java/com/auth0/authentication/{ => result}/Delegation.java (96%) rename core/src/main/java/com/auth0/{ => authentication/result}/Token.java (98%) rename core/src/main/java/com/auth0/{ => authentication/result}/UserIdentity.java (99%) rename core/src/main/java/com/auth0/{ => authentication/result}/UserProfile.java (98%) rename core/src/main/java/com/auth0/{authentication/api => }/callback/BaseCallback.java (96%) rename core/src/main/java/com/auth0/{authentication/api => }/callback/Callback.java (96%) rename core/src/main/java/com/auth0/{authentication/api => }/internal/BaseRequest.java (94%) rename core/src/main/java/com/auth0/{authentication/api => }/internal/JsonRequestBodyBuilder.java (94%) rename core/src/main/java/com/auth0/{authentication/api => }/internal/RequestFactory.java (95%) rename core/src/main/java/com/auth0/{authentication/api => }/internal/SimpleRequest.java (94%) rename core/src/main/java/com/auth0/{authentication/api => }/internal/VoidRequest.java (96%) rename core/src/main/java/com/auth0/{authentication/api => request}/AuthorizableRequest.java (97%) rename core/src/main/java/com/auth0/{authentication/api => request}/ParameterizableRequest.java (97%) rename core/src/main/java/com/auth0/{authentication/api => request}/Request.java (94%) rename core/src/main/java/com/auth0/{authentication/api => }/util/CheckHelper.java (97%) rename core/src/test/java/com/auth0/authentication/{api => }/ParameterBuilderTest.java (99%) rename core/src/test/java/com/auth0/{authentication/api => }/internal/BaseRequestTest.java (95%) rename core/src/test/java/com/auth0/{authentication/api => }/util/AuthenticationAPI.java (99%) rename core/src/test/java/com/auth0/{authentication/api => }/util/CallbackMatcher.java (98%) rename core/src/test/java/com/auth0/{authentication/api => }/util/MockBaseCallback.java (95%) diff --git a/core/src/main/java/com/auth0/authentication/api/APIException.java b/core/src/main/java/com/auth0/APIException.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/APIException.java rename to core/src/main/java/com/auth0/APIException.java index 5c044976..da54242f 100644 --- a/core/src/main/java/com/auth0/authentication/api/APIException.java +++ b/core/src/main/java/com/auth0/APIException.java @@ -22,9 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; - -import com.auth0.Auth0Exception; +package com.auth0; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java b/core/src/main/java/com/auth0/RequestBodyBuildException.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java rename to core/src/main/java/com/auth0/RequestBodyBuildException.java index 10b1e611..2a8528b6 100644 --- a/core/src/main/java/com/auth0/authentication/api/RequestBodyBuildException.java +++ b/core/src/main/java/com/auth0/RequestBodyBuildException.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0; import com.auth0.Auth0Exception; diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 524ebe97..cd471fe5 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -24,21 +24,21 @@ package com.auth0.authentication; -import com.auth0.authentication.api.ParameterBuilder; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; -import com.auth0.authentication.api.internal.RequestFactory; import com.auth0.Auth0; -import com.auth0.DatabaseUser; -import com.auth0.Token; -import com.auth0.UserProfile; +import com.auth0.authentication.result.DatabaseUser; +import com.auth0.authentication.result.Delegation; +import com.auth0.authentication.result.Token; +import com.auth0.authentication.result.UserProfile; +import com.auth0.internal.RequestFactory; +import com.auth0.request.ParameterizableRequest; +import com.auth0.request.Request; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; import java.util.Map; -import static com.auth0.authentication.api.ParameterBuilder.GRANT_TYPE_PASSWORD; +import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_PASSWORD; /** * API client for Auth0 Authentication API. diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java index f0d00910..cb8c0cdd 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -25,12 +25,12 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.ParameterBuilder; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; -import com.auth0.authentication.api.callback.BaseCallback; -import com.auth0.Token; -import com.auth0.UserProfile; +import com.auth0.request.ParameterizableRequest; +import com.auth0.request.Request; +import com.auth0.callback.BaseCallback; +import com.auth0.authentication.result.Token; +import com.auth0.authentication.result.UserProfile; +import com.auth0.authentication.result.Authentication; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index 58b3a07e..e12df904 100644 --- a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -25,8 +25,8 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.request.ParameterizableRequest; +import com.auth0.callback.BaseCallback; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/core/src/main/java/com/auth0/authentication/DelegationRequest.java index 2ebc93da..852f1b02 100644 --- a/core/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/core/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -25,10 +25,10 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.ParameterBuilder; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.request.ParameterizableRequest; +import com.auth0.request.Request; +import com.auth0.callback.BaseCallback; +import com.auth0.authentication.result.Delegation; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java b/core/src/main/java/com/auth0/authentication/ParameterBuilder.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java rename to core/src/main/java/com/auth0/authentication/ParameterBuilder.java index c69f088d..1b6b4435 100644 --- a/core/src/main/java/com/auth0/authentication/api/ParameterBuilder.java +++ b/core/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -22,10 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0.authentication; -import com.auth0.authentication.PasswordlessType; -import com.auth0.authentication.api.util.CheckHelper; +import com.auth0.util.CheckHelper; import java.util.HashMap; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/SignUpRequest.java b/core/src/main/java/com/auth0/authentication/SignUpRequest.java index 15fc7999..a2b12842 100644 --- a/core/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/core/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -25,10 +25,11 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.Request; -import com.auth0.authentication.api.callback.BaseCallback; -import com.auth0.DatabaseUser; +import com.auth0.request.ParameterizableRequest; +import com.auth0.request.Request; +import com.auth0.callback.BaseCallback; +import com.auth0.authentication.result.DatabaseUser; +import com.auth0.authentication.result.Authentication; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java b/core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java deleted file mode 100644 index 8b50af8a..00000000 --- a/core/src/main/java/com/auth0/authentication/api/callback/AuthenticationCallback.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * AuthenticationCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.callback; - -import com.auth0.Token; -import com.auth0.UserProfile; - -/** - * Callback for authentication API calls to Auth0 API. - */ -public interface AuthenticationCallback extends Callback { - - /** - * Called when authentication is successful. - * It might include user's profile and token information. - * @param profile User's profile information or null. - * @param token User's token information (e.g. id_token). - */ - void onSuccess(UserProfile profile, Token token); - -} diff --git a/core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java b/core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java deleted file mode 100644 index 337661bc..00000000 --- a/core/src/main/java/com/auth0/authentication/api/callback/RefreshIdTokenCallback.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * RefreshIdTokenCallback.java - * - * Copyright (c) 2015 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication.api.callback; - -/** - * Callback used in delegation api request for a new Auth0 id_token - */ -public interface RefreshIdTokenCallback extends Callback { - - /** - * Called in successful delegation api call with new id_token - * @param idToken new id_token. - * @param tokenType type of token. - * @param expiresIn when the token expires. - */ - void onSuccess(String idToken, String tokenType, int expiresIn); -} diff --git a/core/src/main/java/com/auth0/authentication/Authentication.java b/core/src/main/java/com/auth0/authentication/result/Authentication.java similarity index 91% rename from core/src/main/java/com/auth0/authentication/Authentication.java rename to core/src/main/java/com/auth0/authentication/result/Authentication.java index 4467991c..6e35f35b 100644 --- a/core/src/main/java/com/auth0/authentication/Authentication.java +++ b/core/src/main/java/com/auth0/authentication/result/Authentication.java @@ -22,13 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.authentication; +package com.auth0.authentication.result; -import com.auth0.Token; -import com.auth0.UserProfile; - -import static com.auth0.authentication.api.util.CheckHelper.checkArgument; +import static com.auth0.util.CheckHelper.checkArgument; /** * The result of a successful authentication against Auth0 diff --git a/core/src/main/java/com/auth0/DatabaseUser.java b/core/src/main/java/com/auth0/authentication/result/DatabaseUser.java similarity index 98% rename from core/src/main/java/com/auth0/DatabaseUser.java rename to core/src/main/java/com/auth0/authentication/result/DatabaseUser.java index 98f7b2b4..2edeca47 100644 --- a/core/src/main/java/com/auth0/DatabaseUser.java +++ b/core/src/main/java/com/auth0/authentication/result/DatabaseUser.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0; +package com.auth0.authentication.result; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/core/src/main/java/com/auth0/authentication/Delegation.java b/core/src/main/java/com/auth0/authentication/result/Delegation.java similarity index 96% rename from core/src/main/java/com/auth0/authentication/Delegation.java rename to core/src/main/java/com/auth0/authentication/result/Delegation.java index 297480cc..1f309491 100644 --- a/core/src/main/java/com/auth0/authentication/Delegation.java +++ b/core/src/main/java/com/auth0/authentication/result/Delegation.java @@ -22,13 +22,13 @@ * THE SOFTWARE. */ -package com.auth0.authentication; +package com.auth0.authentication.result; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import static com.auth0.authentication.api.util.CheckHelper.checkArgument; +import static com.auth0.util.CheckHelper.checkArgument; /** * The result of a successful delegation to an Auth0 app. diff --git a/core/src/main/java/com/auth0/Token.java b/core/src/main/java/com/auth0/authentication/result/Token.java similarity index 98% rename from core/src/main/java/com/auth0/Token.java rename to core/src/main/java/com/auth0/authentication/result/Token.java index 4f69d9ea..1c0bb909 100644 --- a/core/src/main/java/com/auth0/Token.java +++ b/core/src/main/java/com/auth0/authentication/result/Token.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0; +package com.auth0.authentication.result; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/core/src/main/java/com/auth0/UserIdentity.java b/core/src/main/java/com/auth0/authentication/result/UserIdentity.java similarity index 99% rename from core/src/main/java/com/auth0/UserIdentity.java rename to core/src/main/java/com/auth0/authentication/result/UserIdentity.java index dc6e7094..1a2a1c17 100644 --- a/core/src/main/java/com/auth0/UserIdentity.java +++ b/core/src/main/java/com/auth0/authentication/result/UserIdentity.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0; +package com.auth0.authentication.result; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/UserProfile.java b/core/src/main/java/com/auth0/authentication/result/UserProfile.java similarity index 98% rename from core/src/main/java/com/auth0/UserProfile.java rename to core/src/main/java/com/auth0/authentication/result/UserProfile.java index 807e7953..a6250d62 100644 --- a/core/src/main/java/com/auth0/UserProfile.java +++ b/core/src/main/java/com/auth0/authentication/result/UserProfile.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0; +package com.auth0.authentication.result; -import com.auth0.authentication.api.util.CheckHelper; +import com.auth0.util.CheckHelper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java b/core/src/main/java/com/auth0/callback/BaseCallback.java similarity index 96% rename from core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java rename to core/src/main/java/com/auth0/callback/BaseCallback.java index 9b109b33..f4085127 100644 --- a/core/src/main/java/com/auth0/authentication/api/callback/BaseCallback.java +++ b/core/src/main/java/com/auth0/callback/BaseCallback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.callback; +package com.auth0.callback; /** * Callback that receives a single value on success. diff --git a/core/src/main/java/com/auth0/authentication/api/callback/Callback.java b/core/src/main/java/com/auth0/callback/Callback.java similarity index 96% rename from core/src/main/java/com/auth0/authentication/api/callback/Callback.java rename to core/src/main/java/com/auth0/callback/Callback.java index 48e3ec6c..ad7992ed 100644 --- a/core/src/main/java/com/auth0/authentication/api/callback/Callback.java +++ b/core/src/main/java/com/auth0/callback/Callback.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.callback; +package com.auth0.callback; import com.auth0.Auth0Exception; diff --git a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java b/core/src/main/java/com/auth0/internal/BaseRequest.java similarity index 94% rename from core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java rename to core/src/main/java/com/auth0/internal/BaseRequest.java index aceed88a..561a2221 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/internal/BaseRequest.java @@ -22,14 +22,14 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.APIException; -import com.auth0.authentication.api.AuthorizableRequest; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.RequestBodyBuildException; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.APIException; +import com.auth0.request.AuthorizableRequest; +import com.auth0.request.ParameterizableRequest; +import com.auth0.RequestBodyBuildException; +import com.auth0.callback.BaseCallback; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; diff --git a/core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java b/core/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java similarity index 94% rename from core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java rename to core/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java index 931ab977..a15992ed 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/JsonRequestBodyBuilder.java +++ b/core/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java @@ -22,9 +22,9 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; -import com.auth0.authentication.api.RequestBodyBuildException; +import com.auth0.RequestBodyBuildException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.MediaType; diff --git a/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java b/core/src/main/java/com/auth0/internal/RequestFactory.java similarity index 95% rename from core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java rename to core/src/main/java/com/auth0/internal/RequestFactory.java index 5ca778c6..dbd54eba 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/internal/RequestFactory.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; -import com.auth0.authentication.api.AuthorizableRequest; -import com.auth0.authentication.api.ParameterizableRequest; +import com.auth0.request.AuthorizableRequest; +import com.auth0.request.ParameterizableRequest; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; diff --git a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java b/core/src/main/java/com/auth0/internal/SimpleRequest.java similarity index 94% rename from core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java rename to core/src/main/java/com/auth0/internal/SimpleRequest.java index a803d8c1..abbe55a8 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/SimpleRequest.java +++ b/core/src/main/java/com/auth0/internal/SimpleRequest.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.APIException; -import com.auth0.authentication.api.ParameterizableRequest; -import com.auth0.authentication.api.RequestBodyBuildException; +import com.auth0.APIException; +import com.auth0.request.ParameterizableRequest; +import com.auth0.RequestBodyBuildException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; diff --git a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java b/core/src/main/java/com/auth0/internal/VoidRequest.java similarity index 96% rename from core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java rename to core/src/main/java/com/auth0/internal/VoidRequest.java index 5a63c6a8..74edb6d2 100644 --- a/core/src/main/java/com/auth0/authentication/api/internal/VoidRequest.java +++ b/core/src/main/java/com/auth0/internal/VoidRequest.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.APIException; +import com.auth0.APIException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.Callback; diff --git a/core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java b/core/src/main/java/com/auth0/request/AuthorizableRequest.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java rename to core/src/main/java/com/auth0/request/AuthorizableRequest.java index e6695525..5e07da62 100644 --- a/core/src/main/java/com/auth0/authentication/api/AuthorizableRequest.java +++ b/core/src/main/java/com/auth0/request/AuthorizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0.request; /** * Interface for a Auth0 request that need Authorization using a JWT diff --git a/core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java b/core/src/main/java/com/auth0/request/ParameterizableRequest.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java rename to core/src/main/java/com/auth0/request/ParameterizableRequest.java index e014675a..fed5ee61 100644 --- a/core/src/main/java/com/auth0/authentication/api/ParameterizableRequest.java +++ b/core/src/main/java/com/auth0/request/ParameterizableRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0.request; import java.util.Map; diff --git a/core/src/main/java/com/auth0/authentication/api/Request.java b/core/src/main/java/com/auth0/request/Request.java similarity index 94% rename from core/src/main/java/com/auth0/authentication/api/Request.java rename to core/src/main/java/com/auth0/request/Request.java index c0338750..d1f2fcde 100644 --- a/core/src/main/java/com/auth0/authentication/api/Request.java +++ b/core/src/main/java/com/auth0/request/Request.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0.request; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.callback.BaseCallback; /** * Defines a request that can be started diff --git a/core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java b/core/src/main/java/com/auth0/util/CheckHelper.java similarity index 97% rename from core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java rename to core/src/main/java/com/auth0/util/CheckHelper.java index 879b1be0..75eef7fc 100644 --- a/core/src/main/java/com/auth0/authentication/api/util/CheckHelper.java +++ b/core/src/main/java/com/auth0/util/CheckHelper.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.util; +package com.auth0.util; /** * A helper to check constructor arguments. diff --git a/core/src/test/java/com/auth0/UserProfileTest.java b/core/src/test/java/com/auth0/UserProfileTest.java index 07af138d..9d960907 100644 --- a/core/src/test/java/com/auth0/UserProfileTest.java +++ b/core/src/test/java/com/auth0/UserProfileTest.java @@ -25,6 +25,9 @@ package com.auth0; +import com.auth0.authentication.result.UserIdentity; +import com.auth0.authentication.result.UserProfile; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 74947b7d..c4b7f04f 100644 --- a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -26,9 +26,13 @@ import com.auth0.*; -import com.auth0.authentication.api.ParameterBuilder; -import com.auth0.authentication.api.util.AuthenticationAPI; -import com.auth0.authentication.api.util.MockBaseCallback; +import com.auth0.util.AuthenticationAPI; +import com.auth0.util.MockBaseCallback; +import com.auth0.authentication.result.Authentication; +import com.auth0.authentication.result.DatabaseUser; +import com.auth0.authentication.result.Delegation; +import com.auth0.authentication.result.Token; +import com.auth0.authentication.result.UserProfile; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.mockwebserver.RecordedRequest; @@ -40,13 +44,13 @@ import java.util.HashMap; import java.util.Map; -import static com.auth0.authentication.api.util.AuthenticationAPI.GENERIC_TOKEN; -import static com.auth0.authentication.api.util.AuthenticationAPI.ID_TOKEN; -import static com.auth0.authentication.api.util.AuthenticationAPI.REFRESH_TOKEN; -import static com.auth0.authentication.api.util.CallbackMatcher.hasNoError; -import static com.auth0.authentication.api.util.CallbackMatcher.hasNoPayloadOfType; -import static com.auth0.authentication.api.util.CallbackMatcher.hasPayload; -import static com.auth0.authentication.api.util.CallbackMatcher.hasPayloadOfType; +import static com.auth0.util.AuthenticationAPI.GENERIC_TOKEN; +import static com.auth0.util.AuthenticationAPI.ID_TOKEN; +import static com.auth0.util.AuthenticationAPI.REFRESH_TOKEN; +import static com.auth0.util.CallbackMatcher.hasNoError; +import static com.auth0.util.CallbackMatcher.hasNoPayloadOfType; +import static com.auth0.util.CallbackMatcher.hasPayload; +import static com.auth0.util.CallbackMatcher.hasPayloadOfType; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; diff --git a/core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java b/core/src/test/java/com/auth0/authentication/ParameterBuilderTest.java similarity index 99% rename from core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java rename to core/src/test/java/com/auth0/authentication/ParameterBuilderTest.java index be6902ab..f009dfc4 100644 --- a/core/src/test/java/com/auth0/authentication/api/ParameterBuilderTest.java +++ b/core/src/test/java/com/auth0/authentication/ParameterBuilderTest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api; +package com.auth0.authentication; import org.hamcrest.Matcher; diff --git a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java b/core/src/test/java/com/auth0/internal/BaseRequestTest.java similarity index 95% rename from core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java rename to core/src/test/java/com/auth0/internal/BaseRequestTest.java index 1e9c2c79..8ef942b1 100644 --- a/core/src/test/java/com/auth0/authentication/api/internal/BaseRequestTest.java +++ b/core/src/test/java/com/auth0/internal/BaseRequestTest.java @@ -22,12 +22,12 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.internal; +package com.auth0.internal; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.RequestBodyBuildException; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.RequestBodyBuildException; +import com.auth0.callback.BaseCallback; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.HttpUrl; diff --git a/core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java b/core/src/test/java/com/auth0/util/AuthenticationAPI.java similarity index 99% rename from core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java rename to core/src/test/java/com/auth0/util/AuthenticationAPI.java index bebff34b..437ab1f7 100644 --- a/core/src/test/java/com/auth0/authentication/api/util/AuthenticationAPI.java +++ b/core/src/test/java/com/auth0/util/AuthenticationAPI.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.util; +package com.auth0.util; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; diff --git a/core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java b/core/src/test/java/com/auth0/util/CallbackMatcher.java similarity index 98% rename from core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java rename to core/src/test/java/com/auth0/util/CallbackMatcher.java index dcfc151e..59e2fb4a 100644 --- a/core/src/test/java/com/auth0/authentication/api/util/CallbackMatcher.java +++ b/core/src/test/java/com/auth0/util/CallbackMatcher.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.util; +package com.auth0.util; import com.jayway.awaitility.core.ConditionTimeoutException; diff --git a/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java b/core/src/test/java/com/auth0/util/MockBaseCallback.java similarity index 95% rename from core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java rename to core/src/test/java/com/auth0/util/MockBaseCallback.java index 90f94fb9..ab521780 100644 --- a/core/src/test/java/com/auth0/authentication/api/util/MockBaseCallback.java +++ b/core/src/test/java/com/auth0/util/MockBaseCallback.java @@ -22,10 +22,10 @@ * THE SOFTWARE. */ -package com.auth0.authentication.api.util; +package com.auth0.util; import com.auth0.Auth0Exception; -import com.auth0.authentication.api.callback.BaseCallback; +import com.auth0.callback.BaseCallback; import java.util.concurrent.Callable; From fa827014fb5434368eb27a93417dc4564dc9d031 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Mon, 25 Jan 2016 17:46:52 -0300 Subject: [PATCH 40/89] Include telemetry header --- core/src/main/java/com/auth0/Auth0.java | 26 ++++++++-- .../AuthenticationAPIClient.java | 16 ++++++- .../java/com/auth0/internal/BaseRequest.java | 6 +-- .../com/auth0/internal/RequestFactory.java | 5 +- core/src/main/java/com/auth0/util/Base64.java | 47 +++++++++++++++++++ .../main/java/com/auth0/util/BaseMetrics.java | 35 ++++++++++++++ .../src/main/java/com/auth0/util/Metrics.java | 10 ++++ .../java/com/auth0/util/BaseMetricsTest.java | 30 ++++++++++++ 8 files changed, 165 insertions(+), 10 deletions(-) create mode 100644 core/src/main/java/com/auth0/util/Base64.java create mode 100644 core/src/main/java/com/auth0/util/BaseMetrics.java create mode 100644 core/src/main/java/com/auth0/util/Metrics.java create mode 100644 core/src/test/java/com/auth0/util/BaseMetricsTest.java diff --git a/core/src/main/java/com/auth0/Auth0.java b/core/src/main/java/com/auth0/Auth0.java index 6ab9536e..bf406fbe 100644 --- a/core/src/main/java/com/auth0/Auth0.java +++ b/core/src/main/java/com/auth0/Auth0.java @@ -25,16 +25,22 @@ package com.auth0; import com.auth0.authentication.AuthenticationAPIClient; +import com.auth0.util.BaseMetrics; +import com.auth0.util.Metrics; import com.squareup.okhttp.HttpUrl; public class Auth0 { + public static final String VERSION = "1.0.0"; + public static final String NAME = "auth0-java"; + private static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; private static final String DOT_AUTH0_DOT_COM = ".auth0.com"; - protected final String clientId; - protected final String domainUrl; - protected final String configurationUrl; + private final String clientId; + private final String domainUrl; + private final String configurationUrl; + private Metrics metrics; public Auth0(String clientId, String domain) { this(clientId, domain, null); @@ -44,6 +50,8 @@ public Auth0(String clientId, String domain, String configurationDomain) { this.clientId = clientId; this.domainUrl = ensureUrlString(domain); this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl); + this.metrics = new BaseMetrics(); + this.metrics.usingLibrary(Auth0.NAME, Auth0.VERSION); } private String resolveConfiguration(String configurationDomain, String domainUrl) { @@ -95,4 +103,16 @@ public String getAuthorizeUrl() { .build() .toString(); } + + public Metrics getMetrics() { + return metrics; + } + + public void setMetrics(Metrics metrics) { + if (metrics == null) { + this.metrics = new BaseMetrics(); + } else { + this.metrics = metrics; + } + } } diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index cd471fe5..a3a15325 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -32,6 +32,8 @@ import com.auth0.internal.RequestFactory; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; +import com.auth0.util.BaseMetrics; +import com.auth0.util.Metrics; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -73,7 +75,7 @@ public AuthenticationAPIClient(Auth0 auth0) { * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). * @param clientID Your application clientID. * @param baseURL Auth0's auth API endpoint - * @param configurationURL Auth0's enpoint where App info can be retrieved. + * @param configurationURL Auth0's endpoint where App info can be retrieved. */ @SuppressWarnings("unused") public AuthenticationAPIClient(String clientID, String baseURL, String configurationURL) { @@ -84,6 +86,10 @@ protected AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper this.auth0 = auth0; this.client = client; this.mapper = mapper; + final Metrics metrics = auth0.getMetrics(); + if (metrics != null) { + RequestFactory.setClientInfo(metrics.getValue()); + } } public String getClientId() { @@ -94,6 +100,14 @@ public String getBaseURL() { return auth0.getDomainUrl(); } + /** + * Set the value of 'User-Agent' header for every request to Auth0 Authentication API + * @param userAgent value to send in every request to Auth0 + */ + public void setUserAgent(String userAgent) { + RequestFactory.setUserAgent(userAgent); + } + /** * Set the default DB connection name used. By default is 'Username-Password-Authentication' * @param defaultDbConnection name to use on every login with DB connection diff --git a/core/src/main/java/com/auth0/internal/BaseRequest.java b/core/src/main/java/com/auth0/internal/BaseRequest.java index 561a2221..c1ccd5d3 100644 --- a/core/src/main/java/com/auth0/internal/BaseRequest.java +++ b/core/src/main/java/com/auth0/internal/BaseRequest.java @@ -24,12 +24,12 @@ package com.auth0.internal; -import com.auth0.Auth0Exception; import com.auth0.APIException; -import com.auth0.request.AuthorizableRequest; -import com.auth0.request.ParameterizableRequest; +import com.auth0.Auth0Exception; import com.auth0.RequestBodyBuildException; import com.auth0.callback.BaseCallback; +import com.auth0.request.AuthorizableRequest; +import com.auth0.request.ParameterizableRequest; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.squareup.okhttp.Callback; diff --git a/core/src/main/java/com/auth0/internal/RequestFactory.java b/core/src/main/java/com/auth0/internal/RequestFactory.java index dbd54eba..9a4b520f 100644 --- a/core/src/main/java/com/auth0/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/internal/RequestFactory.java @@ -26,6 +26,7 @@ import com.auth0.request.AuthorizableRequest; import com.auth0.request.ParameterizableRequest; +import com.auth0.util.Metrics; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -37,8 +38,6 @@ public class RequestFactory { private static String CLIENT_INFO; private static String USER_AGENT; - protected RequestFactory() {} - public static void setClientInfo(String clientInfo) { CLIENT_INFO = clientInfo; } @@ -85,7 +84,7 @@ public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient cli private static ParameterizableRequest addMetricHeader(ParameterizableRequest request) { if (CLIENT_INFO != null) { - request.addHeader("Auth0-Client", CLIENT_INFO); + request.addHeader(Metrics.HEADER_NAME, CLIENT_INFO); } if (USER_AGENT != null) { request.addHeader("User-Agent", USER_AGENT); diff --git a/core/src/main/java/com/auth0/util/Base64.java b/core/src/main/java/com/auth0/util/Base64.java new file mode 100644 index 00000000..89435a50 --- /dev/null +++ b/core/src/main/java/com/auth0/util/Base64.java @@ -0,0 +1,47 @@ +package com.auth0.util; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; + +public class Base64 { + + private static final byte[] ENCODE_MAP = new byte[] { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '-', '_' + }; + + public static String encodeUrlSafe(String string) { + byte[] in = string.getBytes(Charset.defaultCharset()); + int length = (in.length + 2) * 4 / 3; + byte[] out = new byte[length]; + int index = 0, end = in.length - in.length % 3; + for (int i = 0; i < end; i += 3) { + out[index++] = ENCODE_MAP[(in[i] & 0xff) >> 2]; + out[index++] = ENCODE_MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)]; + out[index++] = ENCODE_MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)]; + out[index++] = ENCODE_MAP[(in[i + 2] & 0x3f)]; + } + switch (in.length % 3) { + case 1: + out[index++] = ENCODE_MAP[(in[end] & 0xff) >> 2]; + out[index++] = ENCODE_MAP[(in[end] & 0x03) << 4]; + out[index++] = '='; + out[index++] = '='; + break; + case 2: + out[index++] = ENCODE_MAP[(in[end] & 0xff) >> 2]; + out[index++] = ENCODE_MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)]; + out[index++] = ENCODE_MAP[((in[end + 1] & 0x0f) << 2)]; + out[index++] = '='; + break; + } + try { + return new String(out, 0, index, "US-ASCII"); + } catch (UnsupportedEncodingException e) { + return null; + } + } + +} diff --git a/core/src/main/java/com/auth0/util/BaseMetrics.java b/core/src/main/java/com/auth0/util/BaseMetrics.java new file mode 100644 index 00000000..768401d3 --- /dev/null +++ b/core/src/main/java/com/auth0/util/BaseMetrics.java @@ -0,0 +1,35 @@ +package com.auth0.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.HashMap; +import java.util.Map; + +public class BaseMetrics implements Metrics { + + private final Map values; + + public BaseMetrics() { + this.values = new HashMap<>(); + } + + @Override + public void usingLibrary(String name, String version) { + values.put(NAME_KEY, name); + values.put(VERSION_KEY, version); + } + + @Override + public String getValue() { + if (values.isEmpty()) { + return null; + } + try { + String json = new ObjectMapper().writeValueAsString(values); + return Base64.encodeUrlSafe(json); + } catch (JsonProcessingException e) { + return null; + } + } +} diff --git a/core/src/main/java/com/auth0/util/Metrics.java b/core/src/main/java/com/auth0/util/Metrics.java new file mode 100644 index 00000000..f60679c2 --- /dev/null +++ b/core/src/main/java/com/auth0/util/Metrics.java @@ -0,0 +1,10 @@ +package com.auth0.util; + +public interface Metrics { + String NAME_KEY = "name"; + String VERSION_KEY = "version"; + String HEADER_NAME = "Auth0-Client"; + + void usingLibrary(String name, String version); + String getValue(); +} diff --git a/core/src/test/java/com/auth0/util/BaseMetricsTest.java b/core/src/test/java/com/auth0/util/BaseMetricsTest.java new file mode 100644 index 00000000..d8e5bdc8 --- /dev/null +++ b/core/src/test/java/com/auth0/util/BaseMetricsTest.java @@ -0,0 +1,30 @@ +package com.auth0.util; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +public class BaseMetricsTest { + + private BaseMetrics metrics; + + @Before + public void setUp() throws Exception { + metrics = new BaseMetrics(); + } + + @Test + public void shouldReturnBase64() throws Exception { + metrics.usingLibrary("auth0-java", "1.0.0"); + assertThat(metrics.getValue(), is(notNullValue())); + } + + @Test + public void shouldReturnNullWhenNoInfoIsProvided() throws Exception { + assertThat(metrics.getValue(), is(nullValue())); + } +} \ No newline at end of file From 6b9b122f1626a36630ef12a7e7c3ee1aa174ad59 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Mon, 25 Jan 2016 18:16:17 -0300 Subject: [PATCH 41/89] RequestFactory has no static methods now. Added some doc to Auth0.java --- core/src/main/java/com/auth0/Auth0.java | 103 +++++++++++++----- .../AuthenticationAPIClient.java | 26 +++-- .../com/auth0/internal/RequestFactory.java | 38 +++---- 3 files changed, 109 insertions(+), 58 deletions(-) diff --git a/core/src/main/java/com/auth0/Auth0.java b/core/src/main/java/com/auth0/Auth0.java index bf406fbe..f2a5b737 100644 --- a/core/src/main/java/com/auth0/Auth0.java +++ b/core/src/main/java/com/auth0/Auth0.java @@ -29,9 +29,22 @@ import com.auth0.util.Metrics; import com.squareup.okhttp.HttpUrl; +/** + * Represents your Auth0 account information (clientId & domain), + * and it's used to obtain clients for Auth0's APIs. + *
{@code
+ * Auth0 auth0 = new Auth0("YOUR_CLIENT_ID", "YOUR_DOMAIN");
+ * }
+ */ public class Auth0 { + /** + * Version of auth0-java + */ public static final String VERSION = "1.0.0"; + /** + * Name of the library auth0-java + */ public static final String NAME = "auth0-java"; private static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com"; @@ -42,10 +55,23 @@ public class Auth0 { private final String configurationUrl; private Metrics metrics; + /** + * Creates a new object using clientId & domain + * @param clientId of your Auth0 application + * @param domain of your Auth0 account + */ public Auth0(String clientId, String domain) { this(clientId, domain, null); } + /** + * Creates a new object using clientId, domain and configuration domain. + * Useful when using a on-premise auth0 server that is not in the public cloud, + * otherwise we recommend using the constructor {@link #Auth0(String, String)} + * @param clientId of your Auth0 application + * @param domain of your Auth0 account + * @param configurationDomain where Auth0's configuration will be fetched. By default is Auth0 public cloud + */ public Auth0(String clientId, String domain, String configurationDomain) { this.clientId = clientId; this.domainUrl = ensureUrlString(domain); @@ -54,49 +80,37 @@ public Auth0(String clientId, String domain, String configurationDomain) { this.metrics.usingLibrary(Auth0.NAME, Auth0.VERSION); } - private String resolveConfiguration(String configurationDomain, String domainUrl) { - String url = ensureUrlString(configurationDomain); - if (configurationDomain == null && domainUrl != null) { - final HttpUrl domainUri = HttpUrl.parse(domainUrl); - final String host = domainUri.host(); - if (host.endsWith(DOT_AUTH0_DOT_COM)) { - String[] parts = host.split("\\."); - if (parts.length > 3) { - url = "https://cdn." + parts[parts.length-3] + DOT_AUTH0_DOT_COM; - } else { - url = AUTH0_US_CDN_URL; - } - } else { - url = domainUrl; - } - } - return url; - } - - private String ensureUrlString(String url) { - String safeUrl = null; - if (url != null) { - safeUrl = url.startsWith("http") ? url : "https://" + url; - } - return safeUrl; - } - + /** + * @return your Auth0 application client identifier + */ public String getClientId() { return clientId; } + /** + * @return your Auth0 account domain url + */ public String getDomainUrl() { return domainUrl; } + /** + * @return your account configuration url + */ public String getConfigurationUrl() { return configurationUrl; } + /** + * @return a new Authentication API client using your account credentials + */ public AuthenticationAPIClient newAuthenticationAPIClient() { return new AuthenticationAPIClient(this); } + /** + * @return Url to perform the web flow of OAuth + */ public String getAuthorizeUrl() { return HttpUrl.parse(domainUrl).newBuilder() .addEncodedPathSegment("authorize") @@ -104,10 +118,17 @@ public String getAuthorizeUrl() { .toString(); } + /** + * @return Auth0 metrics sent in every requests + */ public Metrics getMetrics() { return metrics; } + /** + * Define what metrics are sent to Auth0 on every request. + * @param metrics to send or nil to send nothing + */ public void setMetrics(Metrics metrics) { if (metrics == null) { this.metrics = new BaseMetrics(); @@ -115,4 +136,32 @@ public void setMetrics(Metrics metrics) { this.metrics = metrics; } } + + private String resolveConfiguration(String configurationDomain, String domainUrl) { + String url = ensureUrlString(configurationDomain); + if (configurationDomain == null && domainUrl != null) { + final HttpUrl domainUri = HttpUrl.parse(domainUrl); + final String host = domainUri.host(); + if (host.endsWith(DOT_AUTH0_DOT_COM)) { + String[] parts = host.split("\\."); + if (parts.length > 3) { + url = "https://cdn." + parts[parts.length-3] + DOT_AUTH0_DOT_COM; + } else { + url = AUTH0_US_CDN_URL; + } + } else { + url = domainUrl; + } + } + return url; + } + + private String ensureUrlString(String url) { + String safeUrl = null; + if (url != null) { + safeUrl = url.startsWith("http") ? url : "https://" + url; + } + return safeUrl; + } + } diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index a3a15325..f08b6bef 100644 --- a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -60,6 +60,7 @@ public class AuthenticationAPIClient { private final Auth0 auth0; private final OkHttpClient client; private final ObjectMapper mapper; + private final RequestFactory factory; private String defaultDbConnection = DEFAULT_DB_CONNECTION; @@ -82,13 +83,14 @@ public AuthenticationAPIClient(String clientID, String baseURL, String configura this(new Auth0(clientID, baseURL, configurationURL)); } - protected AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { + private AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { this.auth0 = auth0; this.client = client; this.mapper = mapper; + this.factory = new RequestFactory(); final Metrics metrics = auth0.getMetrics(); if (metrics != null) { - RequestFactory.setClientInfo(metrics.getValue()); + factory.setClientInfo(metrics.getValue()); } } @@ -105,7 +107,7 @@ public String getBaseURL() { * @param userAgent value to send in every request to Auth0 */ public void setUserAgent(String userAgent) { - RequestFactory.setUserAgent(userAgent); + factory.setUserAgent(userAgent); } /** @@ -150,7 +152,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .asDictionary(); final ParameterizableRequest profileRequest = profileRequest(); - ParameterizableRequest credentialsRequest = RequestFactory.POST(url, client, mapper, Token.class) + ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Token.class) .addParameters(parameters); return new AuthenticationRequest(credentialsRequest, profileRequest); } @@ -222,7 +224,7 @@ public ParameterizableRequest createUser(String email, String pass .setConnection(defaultDbConnection) .setClientId(getClientId()) .asDictionary(); - return RequestFactory.POST(url, client, mapper, DatabaseUser.class) + return factory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); } @@ -280,7 +282,7 @@ public ChangePasswordRequest changePassword(String email) { .setConnection(defaultDbConnection) .asDictionary(); - ParameterizableRequest request = RequestFactory.POST(url, client, mapper) + ParameterizableRequest request = factory.POST(url, client, mapper) .addParameters(parameters); return new ChangePasswordRequest(request); } @@ -369,7 +371,7 @@ public Request unlink(String userId, String accessToken) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("unlink") .build(); - return RequestFactory.POST(url, client, mapper) + return factory.POST(url, client, mapper) .addParameters(parameters); } @@ -421,7 +423,7 @@ public ParameterizableRequest> delegation() { .setClientId(getClientId()) .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) .asDictionary(); - return RequestFactory.rawPOST(url, client, mapper) + return factory.rawPOST(url, client, mapper) .addParameters(parameters); } @@ -434,7 +436,7 @@ protected ParameterizableRequest delegation(Class clazz) { .setClientId(getClientId()) .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) .asDictionary(); - return RequestFactory.POST(url, client, mapper, clazz) + return factory.POST(url, client, mapper, clazz) .addParameters(parameters); } @@ -453,7 +455,7 @@ public ParameterizableRequest passwordless() { .setClientId(getClientId()) .asDictionary(); - return RequestFactory.POST(url, client, mapper) + return factory.POST(url, client, mapper) .addParameters(parameters); } @@ -467,7 +469,7 @@ protected ParameterizableRequest loginWithResourceOwner() { .setClientId(getClientId()) .setConnection(defaultDbConnection) .asDictionary(); - ParameterizableRequest request = RequestFactory.POST(url, client, mapper, Token.class) + ParameterizableRequest request = factory.POST(url, client, mapper, Token.class) .addParameters(requestParameters); return request; } @@ -476,7 +478,7 @@ private ParameterizableRequest profileRequest() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("tokeninfo") .build(); - return RequestFactory.POST(url, client, mapper, UserProfile.class); + return factory.POST(url, client, mapper, UserProfile.class); } diff --git a/core/src/main/java/com/auth0/internal/RequestFactory.java b/core/src/main/java/com/auth0/internal/RequestFactory.java index 9a4b520f..3294d41b 100644 --- a/core/src/main/java/com/auth0/internal/RequestFactory.java +++ b/core/src/main/java/com/auth0/internal/RequestFactory.java @@ -35,59 +35,59 @@ public class RequestFactory { - private static String CLIENT_INFO; - private static String USER_AGENT; + private String clientInfo; + private String userAgent; - public static void setClientInfo(String clientInfo) { - CLIENT_INFO = clientInfo; + public void setClientInfo(String clientInfo) { + this.clientInfo = clientInfo; } - public static void setUserAgent(String userAgent) { - USER_AGENT = userAgent; + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; } - public static ParameterizableRequest GET(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + public ParameterizableRequest GET(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "POST", clazz)); } - public static ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + public ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { final SimpleRequest> request = new SimpleRequest<>(url, client, mapper, "POST"); addMetricHeader(request); return request; } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { return addMetricHeader(new VoidRequest(url, client, mapper, "POST")); } - public static ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String jwt) { + public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String jwt) { final AuthorizableRequest request = new VoidRequest(url, client, mapper, "POST") .setBearer(jwt); return addMetricHeader(request); } - public static ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + public ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "PUT", clazz)); } - public static ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + public ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); } - public static ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { + public ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { return addMetricHeader(new SimpleRequest<>(url, client, mapper, "DELETE", clazz)); } - private static ParameterizableRequest addMetricHeader(ParameterizableRequest request) { - if (CLIENT_INFO != null) { - request.addHeader(Metrics.HEADER_NAME, CLIENT_INFO); + private ParameterizableRequest addMetricHeader(ParameterizableRequest request) { + if (this.clientInfo != null) { + request.addHeader(Metrics.HEADER_NAME, this.clientInfo); } - if (USER_AGENT != null) { - request.addHeader("User-Agent", USER_AGENT); + if (this.userAgent!= null) { + request.addHeader("User-Agent", this.userAgent); } return request; } From 824ccb0e21371066fc9c02ec61bba30861930270 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Mon, 25 Jan 2016 19:00:04 -0300 Subject: [PATCH 42/89] Some cleanup --- build.gradle | 1 - {core => lib}/build.gradle | 1 - {core => lib}/src/main/java/com/auth0/APIException.java | 0 {core => lib}/src/main/java/com/auth0/Auth0.java | 0 {core => lib}/src/main/java/com/auth0/Auth0Exception.java | 0 .../src/main/java/com/auth0/RequestBodyBuildException.java | 0 .../com/auth0/authentication/AuthenticationAPIClient.java | 0 .../java/com/auth0/authentication/AuthenticationRequest.java | 0 .../java/com/auth0/authentication/ChangePasswordRequest.java | 0 .../main/java/com/auth0/authentication/DelegationRequest.java | 0 .../main/java/com/auth0/authentication/ParameterBuilder.java | 0 .../main/java/com/auth0/authentication/PasswordlessType.java | 0 .../src/main/java/com/auth0/authentication/SignUpRequest.java | 0 .../java/com/auth0/authentication/result/Authentication.java | 0 .../java/com/auth0/authentication/result/DatabaseUser.java | 0 .../main/java/com/auth0/authentication/result/Delegation.java | 0 .../src/main/java/com/auth0/authentication/result/Token.java | 0 .../java/com/auth0/authentication/result/UserIdentity.java | 0 .../java/com/auth0/authentication/result/UserProfile.java | 0 .../src/main/java/com/auth0/callback/BaseCallback.java | 0 {core => lib}/src/main/java/com/auth0/callback/Callback.java | 0 .../src/main/java/com/auth0/internal/BaseRequest.java | 0 .../main/java/com/auth0/internal/JsonRequestBodyBuilder.java | 0 .../src/main/java/com/auth0/internal/RequestFactory.java | 0 .../src/main/java/com/auth0/internal/SimpleRequest.java | 0 .../src/main/java/com/auth0/internal/VoidRequest.java | 0 .../src/main/java/com/auth0/request/AuthorizableRequest.java | 0 .../main/java/com/auth0/request/ParameterizableRequest.java | 0 {core => lib}/src/main/java/com/auth0/request/Request.java | 0 {core => lib}/src/main/java/com/auth0/util/Base64.java | 0 {core => lib}/src/main/java/com/auth0/util/BaseMetrics.java | 0 {core => lib}/src/main/java/com/auth0/util/CheckHelper.java | 0 {core => lib}/src/main/java/com/auth0/util/Metrics.java | 0 {core => lib}/src/test/java/com/auth0/Auth0Test.java | 0 {core => lib}/src/test/java/com/auth0/UserProfileTest.java | 0 .../com/auth0/authentication/AuthenticationAPIClientTest.java | 0 .../java/com/auth0/authentication/ParameterBuilderTest.java | 0 .../src/test/java/com/auth0/internal/BaseRequestTest.java | 0 .../src/test/java/com/auth0/util/AuthenticationAPI.java | 0 .../src/test/java/com/auth0/util/BaseMetricsTest.java | 0 .../src/test/java/com/auth0/util/CallbackMatcher.java | 0 .../src/test/java/com/auth0/util/MockBaseCallback.java | 0 settings.gradle | 4 ++-- 43 files changed, 2 insertions(+), 4 deletions(-) rename {core => lib}/build.gradle (94%) rename {core => lib}/src/main/java/com/auth0/APIException.java (100%) rename {core => lib}/src/main/java/com/auth0/Auth0.java (100%) rename {core => lib}/src/main/java/com/auth0/Auth0Exception.java (100%) rename {core => lib}/src/main/java/com/auth0/RequestBodyBuildException.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/AuthenticationRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/ChangePasswordRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/DelegationRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/ParameterBuilder.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/PasswordlessType.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/SignUpRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/Authentication.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/DatabaseUser.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/Delegation.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/Token.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/UserIdentity.java (100%) rename {core => lib}/src/main/java/com/auth0/authentication/result/UserProfile.java (100%) rename {core => lib}/src/main/java/com/auth0/callback/BaseCallback.java (100%) rename {core => lib}/src/main/java/com/auth0/callback/Callback.java (100%) rename {core => lib}/src/main/java/com/auth0/internal/BaseRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java (100%) rename {core => lib}/src/main/java/com/auth0/internal/RequestFactory.java (100%) rename {core => lib}/src/main/java/com/auth0/internal/SimpleRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/internal/VoidRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/request/AuthorizableRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/request/ParameterizableRequest.java (100%) rename {core => lib}/src/main/java/com/auth0/request/Request.java (100%) rename {core => lib}/src/main/java/com/auth0/util/Base64.java (100%) rename {core => lib}/src/main/java/com/auth0/util/BaseMetrics.java (100%) rename {core => lib}/src/main/java/com/auth0/util/CheckHelper.java (100%) rename {core => lib}/src/main/java/com/auth0/util/Metrics.java (100%) rename {core => lib}/src/test/java/com/auth0/Auth0Test.java (100%) rename {core => lib}/src/test/java/com/auth0/UserProfileTest.java (100%) rename {core => lib}/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java (100%) rename {core => lib}/src/test/java/com/auth0/authentication/ParameterBuilderTest.java (100%) rename {core => lib}/src/test/java/com/auth0/internal/BaseRequestTest.java (100%) rename {core => lib}/src/test/java/com/auth0/util/AuthenticationAPI.java (100%) rename {core => lib}/src/test/java/com/auth0/util/BaseMetricsTest.java (100%) rename {core => lib}/src/test/java/com/auth0/util/CallbackMatcher.java (100%) rename {core => lib}/src/test/java/com/auth0/util/MockBaseCallback.java (100%) diff --git a/build.gradle b/build.gradle index 442acd8d..25a86166 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,6 @@ allprojects { version = '0.0.1-SNAPSHOT' repositories { - mavenCentral() jcenter() } } diff --git a/core/build.gradle b/lib/build.gradle similarity index 94% rename from core/build.gradle rename to lib/build.gradle index 97ff6229..17e46290 100644 --- a/core/build.gradle +++ b/lib/build.gradle @@ -5,7 +5,6 @@ dependencies { compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1' compile 'com.fasterxml.jackson.core:jackson-core:2.4.1' compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.1' - compile 'org.json:json:20151123' testCompile 'junit:junit:4.12' testCompile 'org.hamcrest:hamcrest-integration:1.3' diff --git a/core/src/main/java/com/auth0/APIException.java b/lib/src/main/java/com/auth0/APIException.java similarity index 100% rename from core/src/main/java/com/auth0/APIException.java rename to lib/src/main/java/com/auth0/APIException.java diff --git a/core/src/main/java/com/auth0/Auth0.java b/lib/src/main/java/com/auth0/Auth0.java similarity index 100% rename from core/src/main/java/com/auth0/Auth0.java rename to lib/src/main/java/com/auth0/Auth0.java diff --git a/core/src/main/java/com/auth0/Auth0Exception.java b/lib/src/main/java/com/auth0/Auth0Exception.java similarity index 100% rename from core/src/main/java/com/auth0/Auth0Exception.java rename to lib/src/main/java/com/auth0/Auth0Exception.java diff --git a/core/src/main/java/com/auth0/RequestBodyBuildException.java b/lib/src/main/java/com/auth0/RequestBodyBuildException.java similarity index 100% rename from core/src/main/java/com/auth0/RequestBodyBuildException.java rename to lib/src/main/java/com/auth0/RequestBodyBuildException.java diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java rename to lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java diff --git a/core/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/AuthenticationRequest.java rename to lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java diff --git a/core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/ChangePasswordRequest.java rename to lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java diff --git a/core/src/main/java/com/auth0/authentication/DelegationRequest.java b/lib/src/main/java/com/auth0/authentication/DelegationRequest.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/DelegationRequest.java rename to lib/src/main/java/com/auth0/authentication/DelegationRequest.java diff --git a/core/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/ParameterBuilder.java rename to lib/src/main/java/com/auth0/authentication/ParameterBuilder.java diff --git a/core/src/main/java/com/auth0/authentication/PasswordlessType.java b/lib/src/main/java/com/auth0/authentication/PasswordlessType.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/PasswordlessType.java rename to lib/src/main/java/com/auth0/authentication/PasswordlessType.java diff --git a/core/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/SignUpRequest.java rename to lib/src/main/java/com/auth0/authentication/SignUpRequest.java diff --git a/core/src/main/java/com/auth0/authentication/result/Authentication.java b/lib/src/main/java/com/auth0/authentication/result/Authentication.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/Authentication.java rename to lib/src/main/java/com/auth0/authentication/result/Authentication.java diff --git a/core/src/main/java/com/auth0/authentication/result/DatabaseUser.java b/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/DatabaseUser.java rename to lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java diff --git a/core/src/main/java/com/auth0/authentication/result/Delegation.java b/lib/src/main/java/com/auth0/authentication/result/Delegation.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/Delegation.java rename to lib/src/main/java/com/auth0/authentication/result/Delegation.java diff --git a/core/src/main/java/com/auth0/authentication/result/Token.java b/lib/src/main/java/com/auth0/authentication/result/Token.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/Token.java rename to lib/src/main/java/com/auth0/authentication/result/Token.java diff --git a/core/src/main/java/com/auth0/authentication/result/UserIdentity.java b/lib/src/main/java/com/auth0/authentication/result/UserIdentity.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/UserIdentity.java rename to lib/src/main/java/com/auth0/authentication/result/UserIdentity.java diff --git a/core/src/main/java/com/auth0/authentication/result/UserProfile.java b/lib/src/main/java/com/auth0/authentication/result/UserProfile.java similarity index 100% rename from core/src/main/java/com/auth0/authentication/result/UserProfile.java rename to lib/src/main/java/com/auth0/authentication/result/UserProfile.java diff --git a/core/src/main/java/com/auth0/callback/BaseCallback.java b/lib/src/main/java/com/auth0/callback/BaseCallback.java similarity index 100% rename from core/src/main/java/com/auth0/callback/BaseCallback.java rename to lib/src/main/java/com/auth0/callback/BaseCallback.java diff --git a/core/src/main/java/com/auth0/callback/Callback.java b/lib/src/main/java/com/auth0/callback/Callback.java similarity index 100% rename from core/src/main/java/com/auth0/callback/Callback.java rename to lib/src/main/java/com/auth0/callback/Callback.java diff --git a/core/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/internal/BaseRequest.java similarity index 100% rename from core/src/main/java/com/auth0/internal/BaseRequest.java rename to lib/src/main/java/com/auth0/internal/BaseRequest.java diff --git a/core/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java b/lib/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java similarity index 100% rename from core/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java rename to lib/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java diff --git a/core/src/main/java/com/auth0/internal/RequestFactory.java b/lib/src/main/java/com/auth0/internal/RequestFactory.java similarity index 100% rename from core/src/main/java/com/auth0/internal/RequestFactory.java rename to lib/src/main/java/com/auth0/internal/RequestFactory.java diff --git a/core/src/main/java/com/auth0/internal/SimpleRequest.java b/lib/src/main/java/com/auth0/internal/SimpleRequest.java similarity index 100% rename from core/src/main/java/com/auth0/internal/SimpleRequest.java rename to lib/src/main/java/com/auth0/internal/SimpleRequest.java diff --git a/core/src/main/java/com/auth0/internal/VoidRequest.java b/lib/src/main/java/com/auth0/internal/VoidRequest.java similarity index 100% rename from core/src/main/java/com/auth0/internal/VoidRequest.java rename to lib/src/main/java/com/auth0/internal/VoidRequest.java diff --git a/core/src/main/java/com/auth0/request/AuthorizableRequest.java b/lib/src/main/java/com/auth0/request/AuthorizableRequest.java similarity index 100% rename from core/src/main/java/com/auth0/request/AuthorizableRequest.java rename to lib/src/main/java/com/auth0/request/AuthorizableRequest.java diff --git a/core/src/main/java/com/auth0/request/ParameterizableRequest.java b/lib/src/main/java/com/auth0/request/ParameterizableRequest.java similarity index 100% rename from core/src/main/java/com/auth0/request/ParameterizableRequest.java rename to lib/src/main/java/com/auth0/request/ParameterizableRequest.java diff --git a/core/src/main/java/com/auth0/request/Request.java b/lib/src/main/java/com/auth0/request/Request.java similarity index 100% rename from core/src/main/java/com/auth0/request/Request.java rename to lib/src/main/java/com/auth0/request/Request.java diff --git a/core/src/main/java/com/auth0/util/Base64.java b/lib/src/main/java/com/auth0/util/Base64.java similarity index 100% rename from core/src/main/java/com/auth0/util/Base64.java rename to lib/src/main/java/com/auth0/util/Base64.java diff --git a/core/src/main/java/com/auth0/util/BaseMetrics.java b/lib/src/main/java/com/auth0/util/BaseMetrics.java similarity index 100% rename from core/src/main/java/com/auth0/util/BaseMetrics.java rename to lib/src/main/java/com/auth0/util/BaseMetrics.java diff --git a/core/src/main/java/com/auth0/util/CheckHelper.java b/lib/src/main/java/com/auth0/util/CheckHelper.java similarity index 100% rename from core/src/main/java/com/auth0/util/CheckHelper.java rename to lib/src/main/java/com/auth0/util/CheckHelper.java diff --git a/core/src/main/java/com/auth0/util/Metrics.java b/lib/src/main/java/com/auth0/util/Metrics.java similarity index 100% rename from core/src/main/java/com/auth0/util/Metrics.java rename to lib/src/main/java/com/auth0/util/Metrics.java diff --git a/core/src/test/java/com/auth0/Auth0Test.java b/lib/src/test/java/com/auth0/Auth0Test.java similarity index 100% rename from core/src/test/java/com/auth0/Auth0Test.java rename to lib/src/test/java/com/auth0/Auth0Test.java diff --git a/core/src/test/java/com/auth0/UserProfileTest.java b/lib/src/test/java/com/auth0/UserProfileTest.java similarity index 100% rename from core/src/test/java/com/auth0/UserProfileTest.java rename to lib/src/test/java/com/auth0/UserProfileTest.java diff --git a/core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java similarity index 100% rename from core/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java rename to lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java diff --git a/core/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java similarity index 100% rename from core/src/test/java/com/auth0/authentication/ParameterBuilderTest.java rename to lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java diff --git a/core/src/test/java/com/auth0/internal/BaseRequestTest.java b/lib/src/test/java/com/auth0/internal/BaseRequestTest.java similarity index 100% rename from core/src/test/java/com/auth0/internal/BaseRequestTest.java rename to lib/src/test/java/com/auth0/internal/BaseRequestTest.java diff --git a/core/src/test/java/com/auth0/util/AuthenticationAPI.java b/lib/src/test/java/com/auth0/util/AuthenticationAPI.java similarity index 100% rename from core/src/test/java/com/auth0/util/AuthenticationAPI.java rename to lib/src/test/java/com/auth0/util/AuthenticationAPI.java diff --git a/core/src/test/java/com/auth0/util/BaseMetricsTest.java b/lib/src/test/java/com/auth0/util/BaseMetricsTest.java similarity index 100% rename from core/src/test/java/com/auth0/util/BaseMetricsTest.java rename to lib/src/test/java/com/auth0/util/BaseMetricsTest.java diff --git a/core/src/test/java/com/auth0/util/CallbackMatcher.java b/lib/src/test/java/com/auth0/util/CallbackMatcher.java similarity index 100% rename from core/src/test/java/com/auth0/util/CallbackMatcher.java rename to lib/src/test/java/com/auth0/util/CallbackMatcher.java diff --git a/core/src/test/java/com/auth0/util/MockBaseCallback.java b/lib/src/test/java/com/auth0/util/MockBaseCallback.java similarity index 100% rename from core/src/test/java/com/auth0/util/MockBaseCallback.java rename to lib/src/test/java/com/auth0/util/MockBaseCallback.java diff --git a/settings.gradle b/settings.gradle index 9ab64ea7..0baf2b62 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,2 @@ -rootProject.name = 'auth0-api-java' -include 'core' +rootProject.name = 'auth0-java' +include 'lib' From d92cf4db2ef446c0e1421dfb8138f28527a8b5d3 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Tue, 26 Jan 2016 19:34:31 -0300 Subject: [PATCH 43/89] let UserProfile implement Serializable --- .../java/com/auth0/authentication/result/UserProfile.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/result/UserProfile.java b/lib/src/main/java/com/auth0/authentication/result/UserProfile.java index a6250d62..5d9a4faf 100644 --- a/lib/src/main/java/com/auth0/authentication/result/UserProfile.java +++ b/lib/src/main/java/com/auth0/authentication/result/UserProfile.java @@ -28,6 +28,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -42,8 +43,7 @@ * Class that holds the information of a user's profile */ @JsonIgnoreProperties(ignoreUnknown = true) -public class UserProfile { - +public class UserProfile implements Serializable { protected String id; protected String name; protected String nickname; @@ -118,6 +118,7 @@ public Date getCreatedAt() { /** * Returns extra information of the profile. + * * @return */ public Map getExtraInfo() { @@ -126,6 +127,7 @@ public Map getExtraInfo() { /** * List of the identities from a Identity Provider associated to the user. + * * @return */ public List getIdentities() { @@ -137,7 +139,7 @@ private List buildIdentities(List> values) { return Collections.emptyList(); } List identities = new ArrayList<>(values.size()); - for (Map value: values) { + for (Map value : values) { identities.add(new UserIdentity(value)); } return identities; From b4938ad3422ba48dd23c0864f52029085eb2f02f Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 12:04:16 -0300 Subject: [PATCH 44/89] make builder constructor private. extract constants --- .../authentication/ParameterBuilder.java | 55 +++++++++++++------ .../authentication/ParameterBuilderTest.java | 10 ---- 2 files changed, 37 insertions(+), 28 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 1b6b4435..b11d5b8b 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -34,90 +34,102 @@ */ public class ParameterBuilder { + public static final String GRANT_TYPE_PASSWORD = "password"; + public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public static final String SCOPE_OPENID = "openid"; public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; - public static final String ACCESS_TOKEN = "access_token"; - public static final String CONNECTION = "connection"; - public static final String SEND = "send"; - public static final String GRANT_TYPE_PASSWORD = "password"; - public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + private static final String ACCESS_TOKEN_KEY = "access_token"; + private static final String CONNECTION_KEY = "connection"; + private static final String SEND_KEY = "send"; + private static final String CLIENT_ID_KEY = "client_id"; + private static final String GRANT_TYPE_KEY = "grant_type"; + private static final String SCOPE_KEY = "scope"; + private static final String DEVICE_KEY = "device"; private Map parameters; /** * Creates a new builder */ - public ParameterBuilder() { + private ParameterBuilder() { this.parameters = new HashMap<>(); setScope(SCOPE_OFFLINE_ACCESS); } /** * Creates a new builder with default parameters + * * @param parameters default parameters */ - public ParameterBuilder(Map parameters) { + private ParameterBuilder(Map parameters) { CheckHelper.checkArgument(parameters != null, "Must provide non-null parameters"); this.parameters = new HashMap<>(parameters); } /** * Sets the 'client_id' parameter + * * @param clientId clientID * @return itself */ public ParameterBuilder setClientId(String clientId) { - return set("client_id", clientId); + return set(CLIENT_ID_KEY, clientId); } /** * Sets the 'grant_type' parameter + * * @param grantType grant type * @return itself */ public ParameterBuilder setGrantType(String grantType) { - return set("grant_type", grantType); + return set(GRANT_TYPE_KEY, grantType); } /** * Sets the 'connection' parameter + * * @param connection name of the connection * @return itself */ public ParameterBuilder setConnection(String connection) { - return set(CONNECTION, connection); + return set(CONNECTION_KEY, connection); } /** * Sets the 'scope' parameter. + * * @param scope a scope value * @return itself */ public ParameterBuilder setScope(String scope) { - return set("scope", scope); + return set(SCOPE_KEY, scope); } /** * Sets the 'device' parameter + * * @param device a device name * @return itself */ public ParameterBuilder setDevice(String device) { - return set("device", device); + return set(DEVICE_KEY, device); } /** * Sets the 'access_token' parameter + * * @param accessToken a access token * @return itself */ public ParameterBuilder setAccessToken(String accessToken) { - return set(ACCESS_TOKEN, accessToken); + return set(ACCESS_TOKEN_KEY, accessToken); } /** * Sets the 'send' parameter + * * @param passwordlessType the type of passwordless login * @return itself */ @@ -125,19 +137,20 @@ public ParameterBuilder setSend(PasswordlessType passwordlessType) { switch (passwordlessType) { default: case CODE: - return set(SEND, "code"); + return set(SEND_KEY, "code"); case LINK: - return set(SEND, "link"); + return set(SEND_KEY, "link"); case LINK_ANDROID: - return set(SEND, "link_android"); + return set(SEND_KEY, "link_android"); case LINK_IOS: - return set(SEND, "link_ios"); + return set(SEND_KEY, "link_ios"); } } /** * Sets a parameter - * @param key parameter name + * + * @param key parameter name * @param value parameter value * @return itself */ @@ -148,6 +161,7 @@ public ParameterBuilder set(String key, Object value) { /** * Adds all parameter from a map + * * @param parameters map with parameters to add * @return itself */ @@ -160,6 +174,7 @@ public ParameterBuilder addAll(Map parameters) { /** * Clears all existing parameters + * * @return itself */ public ParameterBuilder clearAll() { @@ -169,6 +184,7 @@ public ParameterBuilder clearAll() { /** * Create a {@link Map} with all the parameters + * * @return a new map with the parameters */ public Map asDictionary() { @@ -177,6 +193,7 @@ public Map asDictionary() { /** * Creates a new instance of the builder with default values + * * @return a new builder */ public static ParameterBuilder newBuilder() { @@ -185,6 +202,7 @@ public static ParameterBuilder newBuilder() { /** * Creates a new instance of the builder without any default values + * * @return a new builder */ public static ParameterBuilder newEmptyBuilder() { @@ -193,6 +211,7 @@ public static ParameterBuilder newEmptyBuilder() { /** * Creates a new instance of the builder with parameters. + * * @param parameters default parameters * @return a new builder */ diff --git a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java index f009dfc4..4d349e0b 100644 --- a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java +++ b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java @@ -59,29 +59,19 @@ public void setUp() throws Exception { @Test public void shouldInstantiateWithNoArguments() throws Exception { - assertThat(new ParameterBuilder(), is(notNullValue())); assertThat(ParameterBuilder.newBuilder(), is(notNullValue())); } @Test public void shouldInstantiateWithDefaultScope() throws Exception { - assertThat(new ParameterBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); assertThat(ParameterBuilder.newBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); } @Test public void shouldInstantiateWithArguments() throws Exception { - assertThat(new ParameterBuilder(new HashMap()), is(notNullValue())); assertThat(ParameterBuilder.newBuilder(new HashMap()), is(notNullValue())); } - @Test - public void shouldFailToInstantiateWithNullParameters() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(equalToIgnoringCase("Must provide non-null parameters")); - new ParameterBuilder(null); - } - @Test public void shouldFailToInstantiateWithNullParametersInFactoryMethod() throws Exception { expectedException.expect(IllegalArgumentException.class); From 1839d6b92e3e7d3315c1af1eed7ea3263043b779 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 14:37:12 -0300 Subject: [PATCH 45/89] refactor ParameterizableRequest, now reveals the ParameterBuilder for direct access usage --- .../AuthenticationAPIClient.java | 215 +++++++++--------- .../authentication/AuthenticationRequest.java | 27 +-- .../authentication/ChangePasswordRequest.java | 27 ++- .../authentication/DelegationRequest.java | 26 ++- .../authentication/ParameterBuilder.java | 2 +- .../auth0/authentication/SignUpRequest.java | 2 +- .../java/com/auth0/internal/BaseRequest.java | 18 +- .../auth0/request/ParameterizableRequest.java | 14 +- .../AuthenticationAPIClientTest.java | 81 ++++--- 9 files changed, 209 insertions(+), 203 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index f08b6bef..a3b09cdc 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -32,7 +32,6 @@ import com.auth0.internal.RequestFactory; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; -import com.auth0.util.BaseMetrics; import com.auth0.util.Metrics; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; @@ -40,10 +39,12 @@ import java.util.Map; +import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_JWT; import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_PASSWORD; /** * API client for Auth0 Authentication API. + * * @see Auth API docs */ public class AuthenticationAPIClient { @@ -66,6 +67,7 @@ public class AuthenticationAPIClient { /** * Creates a new API client instance providing Auth0 account info. + * * @param auth0 account information */ public AuthenticationAPIClient(Auth0 auth0) { @@ -74,8 +76,9 @@ public AuthenticationAPIClient(Auth0 auth0) { /** * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). - * @param clientID Your application clientID. - * @param baseURL Auth0's auth API endpoint + * + * @param clientID Your application clientID. + * @param baseURL Auth0's auth API endpoint * @param configurationURL Auth0's endpoint where App info can be retrieved. */ @SuppressWarnings("unused") @@ -104,6 +107,7 @@ public String getBaseURL() { /** * Set the value of 'User-Agent' header for every request to Auth0 Authentication API + * * @param userAgent value to send in every request to Auth0 */ public void setUserAgent(String userAgent) { @@ -112,6 +116,7 @@ public void setUserAgent(String userAgent) { /** * Set the default DB connection name used. By default is 'Username-Password-Authentication' + * * @param defaultDbConnection name to use on every login with DB connection */ public void setDefaultDbConnection(String defaultDbConnection) { @@ -120,12 +125,13 @@ public void setDefaultDbConnection(String defaultDbConnection) { /** * Log in a user with email/username and password using a DB connection and fetch it's profile from Auth0 + * * @param usernameOrEmail of the user depending of the type of DB connection - * @param password of the user + * @param password of the user * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ public AuthenticationRequest login(String usernameOrEmail, String password) { - Map requestParameters = new ParameterBuilder() + Map requestParameters = ParameterBuilder.newBuilder() .set(USERNAME_KEY, usernameOrEmail) .set(PASSWORD_KEY, password) .setGrantType(GRANT_TYPE_PASSWORD) @@ -135,7 +141,8 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { /** * Log in a user with a OAuth 'access_token' of a Identity Provider like Facebook or Twitter using '\oauth\access_token' endpoint - * @param token obtained from the IdP + * + * @param token obtained from the IdP * @param connection that will be used to authenticate the user, e.g. 'facebook' * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ @@ -152,14 +159,15 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .asDictionary(); final ParameterizableRequest profileRequest = profileRequest(); - ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Token.class) - .addParameters(parameters); + ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Token.class); + credentialsRequest.getParameterBuilder().addAll(parameters); return new AuthenticationRequest(credentialsRequest, profileRequest); } /** * Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) - * @param phoneNumber where the user received the verification code + * + * @param phoneNumber where the user received the verification code * @param verificationCode sent by Auth0 via SMS * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ @@ -176,7 +184,8 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver /** * Log in a user using an email and a verification code received via Email (Part of passwordless login flow) - * @param email where the user received the verification code + * + * @param email where the user received the verification code * @param verificationCode sent by Auth0 via Email * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ @@ -193,21 +202,20 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod /** * Fetch the token information from Auth0 + * * @param idToken used to fetch it's information * @return a request to start */ public Request tokenInfo(String idToken) { - Map requestParameters = new ParameterBuilder() - .clearAll() - .set(ID_TOKEN_KEY, idToken) - .asDictionary(); - return profileRequest() - .addParameters(requestParameters); + ParameterizableRequest request = profileRequest(); + request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + return request; } /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint - * @param email of the user and must be non null + * + * @param email of the user and must be non null * @param password of the user and must be non null * @param username of the user and must be non null * @return a request to start @@ -217,20 +225,21 @@ public ParameterizableRequest createUser(String email, String pass .addPathSegment("dbconnections") .addPathSegment("signup") .build(); - Map parameters = new ParameterBuilder() + + ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class); + request.getParameterBuilder() .set(USERNAME_KEY, username) .set(EMAIL_KEY, email) .set(PASSWORD_KEY, password) .setConnection(defaultDbConnection) - .setClientId(getClientId()) - .asDictionary(); - return factory.POST(url, client, mapper, DatabaseUser.class) - .addParameters(parameters); + .setClientId(getClientId()); + return request; } /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint - * @param email of the user and must be non null + * + * @param email of the user and must be non null * @param password of the user and must be non null * @return a request to start */ @@ -241,7 +250,8 @@ public ParameterizableRequest createUser(String email, String pass /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint * and then logs in and fetches it's user profile - * @param email of the user and must be non null + * + * @param email of the user and must be non null * @param password of the user and must be non null * @param username of the user and must be non null * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} @@ -255,7 +265,8 @@ public SignUpRequest signUp(String email, String password, String username) { /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint * and then logs in and fetches it's user profile - * @param email of the user and must be non null + * + * @param email of the user and must be non null * @param password of the user and must be non null * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ @@ -267,6 +278,7 @@ public SignUpRequest signUp(String email, String password) { /** * Perform a change password request using '/dbconnections/change_password' + * * @param email of the user that changes the password. It's also where the confirmation email will be sent * @return a request to configure and start */ @@ -276,29 +288,24 @@ public ChangePasswordRequest changePassword(String email) { .addPathSegment("change_password") .build(); - Map parameters = ParameterBuilder.newBuilder() + ParameterizableRequest request = factory.POST(url, client, mapper); + request.getParameterBuilder() .set(EMAIL_KEY, email) .setClientId(getClientId()) - .setConnection(defaultDbConnection) - .asDictionary(); - - ParameterizableRequest request = factory.POST(url, client, mapper) - .addParameters(parameters); + .setConnection(defaultDbConnection); return new ChangePasswordRequest(request); } /** * Performs a delegation request that will yield a new Auth0 'id_token' + * * @param idToken issued by Auth0 for the user. The token must not be expired. * @return a request to configure and start */ public DelegationRequest delegationWithIdToken(String idToken) { - Map parameters = new ParameterBuilder() - .clearAll() - .set(ID_TOKEN_KEY, idToken) - .asDictionary(); - ParameterizableRequest request = delegation(Delegation.class) - .addParameters(parameters); + ParameterizableRequest request = delegation(Delegation.class); + request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); } @@ -306,33 +313,29 @@ public DelegationRequest delegationWithIdToken(String idToken) { /** * Performs a delegation request that will yield a new Auth0 'id_token'. * Check our refresh token docs for more information + * * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. * @return a request to configure and start */ public DelegationRequest delegationWithRefreshToken(String refreshToken) { - Map parameters = new ParameterBuilder() - .clearAll() - .set(REFRESH_TOKEN_KEY, refreshToken) - .asDictionary(); - ParameterizableRequest request = delegation(Delegation.class) - .addParameters(parameters); + ParameterizableRequest request = delegation(Delegation.class); + request.getParameterBuilder().set(REFRESH_TOKEN_KEY, refreshToken); + return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); } /** * Performs a delegation request that will yield a delegation token. + * * @param idToken issued by Auth0 for the user. The token must not be expired. * @param apiType the delegation 'api_type' parameter * @return a request to configure and start */ - public DelegationRequest> delegationWithIdToken(String idToken, String apiType) { - Map parameters = new ParameterBuilder() - .clearAll() - .set(ID_TOKEN_KEY, idToken) - .asDictionary(); - ParameterizableRequest> request = delegation() - .addParameters(parameters); + public DelegationRequest> delegationWithIdToken(String idToken, String apiType) { + ParameterizableRequest> request = delegation(); + request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + return new DelegationRequest<>(request) .setApiType(apiType); } @@ -340,108 +343,105 @@ public DelegationRequest> delegationWithIdToken(String idToke /** * Performs a delegation request that will yield a delegation token. * Check our refresh token docs for more information + * * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. - * @param apiType the delegation 'api_type' parameter + * @param apiType the delegation 'api_type' parameter * @return a request to configure and start */ - public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { - Map parameters = new ParameterBuilder() - .clearAll() - .set(REFRESH_TOKEN_KEY, refreshToken) - .asDictionary(); - ParameterizableRequest> request = delegation() - .addParameters(parameters); - return new DelegationRequest<>(request) - .setApiType(apiType); + public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { + ParameterizableRequest> request = delegation(); + request.getParameterBuilder().set(REFRESH_TOKEN_KEY, refreshToken); + + return new DelegationRequest<>(request).setApiType(apiType); } /** * Unlink a user identity calling '/unlink' endpoint - * @param userId of the identity to unlink + * + * @param userId of the identity to unlink * @param accessToken of the main identity obtained after login * @return a request to start */ public Request unlink(String userId, String accessToken) { - Map parameters = new ParameterBuilder() - .clearAll() - .set("clientID", getClientId()) - .set("user_id", userId) - .set("access_token", accessToken) - .asDictionary(); + //TODO: Test this after removing .set("clientID", getClientId()) HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("unlink") .build(); - return factory.POST(url, client, mapper) - .addParameters(parameters); + + ParameterizableRequest request = factory.POST(url, client, mapper); + request.getParameterBuilder() + .setClientId(getClientId()) + .setAccessToken(accessToken) + .set("user_id", userId); + return request; } /** * Start a passwordless flow with Email - * @param email that will receive a verification code to use for login + * + * @param email that will receive a verification code to use for login * @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS) * @return a request to configure and start */ public ParameterizableRequest passwordlessWithEmail(String email, PasswordlessType passwordlessType) { - Map parameters = ParameterBuilder.newBuilder() - .clearAll() + ParameterizableRequest request = passwordless(); + request.getParameterBuilder() .set(EMAIL_KEY, email) .setSend(passwordlessType) - .setConnection("email") - .asDictionary(); - return passwordless() - .addParameters(parameters); + .setConnection("email"); + return request; } /** * Start a passwordless flow with SMS - * @param phoneNumber where an SMS with a verification code will be sent + * + * @param phoneNumber where an SMS with a verification code will be sent * @param passwordlessType indicate whether the SMS should contain a code, link or magic link (android & iOS) * @return a request to configure and start */ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, PasswordlessType passwordlessType) { - Map parameters = ParameterBuilder.newBuilder() - .clearAll() + ParameterizableRequest request = passwordless(); + request.getParameterBuilder() .set(PHONE_NUMBER_KEY, phoneNumber) .setSend(passwordlessType) - .setConnection("sms") - .asDictionary(); - return passwordless() - .addParameters(parameters); + .setConnection("sms"); + return request; } /** * Performs a custom delegation request that will * yield a delegation token. + * * @return a request to configure and start */ public ParameterizableRequest> delegation() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("delegation") .build(); - Map parameters = ParameterBuilder.newEmptyBuilder() - .clearAll() + + ParameterizableRequest> request = factory.rawPOST(url, client, mapper); + request.getParameterBuilder() .setClientId(getClientId()) - .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) - .asDictionary(); - return factory.rawPOST(url, client, mapper) - .addParameters(parameters); + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT); + return request; } protected ParameterizableRequest delegation(Class clazz) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("delegation") .build(); - Map parameters = ParameterBuilder.newEmptyBuilder() - .clearAll() + + ParameterizableRequest request = factory.POST(url, client, mapper, clazz); + request.getParameterBuilder() .setClientId(getClientId()) - .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) - .asDictionary(); - return factory.POST(url, client, mapper, clazz) - .addParameters(parameters); + .setGrantType(GRANT_TYPE_JWT); + + return request; } /** * Start a custom passwordless flow + * * @return a request to configure and start */ public ParameterizableRequest passwordless() { @@ -450,27 +450,21 @@ public ParameterizableRequest passwordless() { .addPathSegment("start") .build(); - Map parameters = ParameterBuilder.newBuilder() - .clearAll() - .setClientId(getClientId()) - .asDictionary(); - - return factory.POST(url, client, mapper) - .addParameters(parameters); + ParameterizableRequest request = factory.POST(url, client, mapper); + request.getParameterBuilder().setClientId(getClientId()); + return request; } - + protected ParameterizableRequest loginWithResourceOwner() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("oauth") .addPathSegment("ro") .build(); - Map requestParameters = new ParameterBuilder() + ParameterizableRequest request = factory.POST(url, client, mapper, Token.class); + request.getParameterBuilder() .setClientId(getClientId()) - .setConnection(defaultDbConnection) - .asDictionary(); - ParameterizableRequest request = factory.POST(url, client, mapper, Token.class) - .addParameters(requestParameters); + .setConnection(defaultDbConnection); return request; } @@ -478,13 +472,14 @@ private ParameterizableRequest profileRequest() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment("tokeninfo") .build(); + return factory.POST(url, client, mapper, UserProfile.class); } private AuthenticationRequest newAuthenticationRequest(Map parameters) { - final ParameterizableRequest credentialsRequest = loginWithResourceOwner() - .addParameters(parameters); + final ParameterizableRequest credentialsRequest = loginWithResourceOwner(); + credentialsRequest.getParameterBuilder().addAll(parameters); final ParameterizableRequest profileRequest = profileRequest(); return new AuthenticationRequest(credentialsRequest, profileRequest); diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java index cb8c0cdd..fabaa385 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -39,6 +39,8 @@ */ public class AuthenticationRequest implements Request { + private static final String ID_TOKEN_KEY = "id_token"; + private final ParameterizableRequest credentialsRequest; private final ParameterizableRequest tokenInfoRequest; @@ -49,36 +51,40 @@ public class AuthenticationRequest implements Request { /** * Adds additional parameters for the login request + * * @param parameters as a non-null dictionary * @return itself */ public AuthenticationRequest addParameters(Map parameters) { - credentialsRequest.addParameters(parameters); + credentialsRequest.getParameterBuilder().addAll(parameters); return this; } /** * Set the scope used to authenticate the user + * * @param scope value * @return itself */ public AuthenticationRequest setScope(String scope) { - credentialsRequest.addParameters(new ParameterBuilder().clearAll().setScope(scope).asDictionary()); + credentialsRequest.getParameterBuilder().setScope(scope); return this; } /** * Set the connection used to authenticate + * * @param connection name * @return itself */ public AuthenticationRequest setConnection(String connection) { - credentialsRequest.addParameters(new ParameterBuilder().clearAll().setConnection(connection).asDictionary()); + credentialsRequest.getParameterBuilder().setConnection(connection); return this; } /** * Starts the log in request and then fetches the user's profile + * * @param callback called on either success or failure */ @Override @@ -86,12 +92,10 @@ public void start(final BaseCallback callback) { credentialsRequest.start(new BaseCallback() { @Override public void onSuccess(final Token token) { - Map parameters = new ParameterBuilder() - .clearAll() - .set("id_token", token.getIdToken()) - .asDictionary(); tokenInfoRequest - .addParameters(parameters) + .getParameterBuilder() + .set(ID_TOKEN_KEY, token.getIdToken()); + tokenInfoRequest .start(new BaseCallback() { @Override public void onSuccess(UserProfile profile) { @@ -114,18 +118,15 @@ public void onFailure(Auth0Exception error) { /** * Logs in the user with Auth0 and fetches it's profile. + * * @return authentication object containing the user's tokens and profile * @throws Auth0Exception when either authentication or profile fetch fails */ @Override public Authentication execute() throws Auth0Exception { Token token = credentialsRequest.execute(); - Map parameters = new ParameterBuilder() - .clearAll() - .set("id_token", token.getIdToken()) - .asDictionary(); + tokenInfoRequest.getParameterBuilder().set(ID_TOKEN_KEY, token.getIdToken()); UserProfile profile = tokenInfoRequest - .addParameters(parameters) .execute(); return new Authentication(profile, token); } diff --git a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index e12df904..e4bdde3b 100644 --- a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -42,37 +42,34 @@ public class ChangePasswordRequest implements ParameterizableRequest { ChangePasswordRequest(ParameterizableRequest request) { this.request = request; - } - - private ChangePasswordRequest addParameter(String key, Object value) { - Map parameters = new HashMap<>(); - parameters.put(key, value); - return addParameters(parameters); + request.getParameterBuilder(); } /** * Set the 'password' parameter to be sent in the request + * * @param newPassword the new password * @return itself */ public ChangePasswordRequest setNewPassword(String newPassword) { - return addParameter(PASSWORD_KEY, newPassword); + request.getParameterBuilder().set(PASSWORD_KEY, newPassword); + return this; } /** - * Adds additional parameters to be sent in the request - * @param parameters as a non-null dictionary - * @return itself + * Getter for this request ParameterBuilder. + * + * @return the associated ParameterBuilder instance */ @Override - public ChangePasswordRequest addParameters(Map parameters) { - request.addParameters(parameters); - return this; + public ParameterBuilder getParameterBuilder() { + return request.getParameterBuilder(); } /** * Adds an additional header for the request - * @param name of the header + * + * @param name of the header * @param value of the header * @return itself */ @@ -84,6 +81,7 @@ public ChangePasswordRequest addHeader(String name, String value) { /** * Starts the change password request + * * @param callback called either on success or failure */ @Override @@ -93,6 +91,7 @@ public void start(final BaseCallback callback) { /** * Executes the change password request + * * @return nothing on success * @throws Auth0Exception when the change password request fails */ diff --git a/lib/src/main/java/com/auth0/authentication/DelegationRequest.java b/lib/src/main/java/com/auth0/authentication/DelegationRequest.java index 852f1b02..eb8ad45e 100644 --- a/lib/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -25,20 +25,20 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; +import com.auth0.authentication.result.Delegation; +import com.auth0.callback.BaseCallback; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; -import com.auth0.callback.BaseCallback; -import com.auth0.authentication.result.Delegation; -import java.util.HashMap; import java.util.Map; /** * Represents a delegation request for Auth0 tokens that will yield a new delegation token. * The delegation response depends on the 'api_type' parameter. + * * @param type of object that will hold the delegation response. When requesting Auth0’s 'id_token' you can - * use {@link Delegation}, otherwise you’ll need to provide an object that can be created from the JSON - * payload or just use {@code Map} + * use {@link Delegation}, otherwise you’ll need to provide an object that can be created from the JSON + * payload or just use {@code Map} */ public class DelegationRequest implements Request { @@ -54,23 +54,24 @@ public class DelegationRequest implements Request { } private DelegationRequest addParameter(String key, Object value) { - Map parameters = new HashMap<>(); - parameters.put(key, value); - return addParameters(parameters); + request.getParameterBuilder().set(key, value); + return this; } /** * Add additional parameters to be sent in the request + * * @param parameters as a non-null dictionary * @return itself */ public DelegationRequest addParameters(Map parameters) { - request.addParameters(parameters); + request.getParameterBuilder().addAll(parameters); return this; } /** * Set the 'api_type' parameter to be sent in the request + * * @param apiType the delegation api type * @return itself */ @@ -80,15 +81,18 @@ public DelegationRequest setApiType(String apiType) { /** * Set the 'scope' used to make the delegation + * * @param scope value * @return itself */ public DelegationRequest setScope(String scope) { - return addParameters(new ParameterBuilder().clearAll().setScope(scope).asDictionary()); + request.getParameterBuilder().setScope(scope); + return this; } /** * Set the 'target' parameter to be sent in the request + * * @param target the delegation target * @return itself */ @@ -98,6 +102,7 @@ public DelegationRequest setTarget(String target) { /** * Starts the delegation request against Auth0 API + * * @param callback called either on success or failure */ @Override @@ -107,6 +112,7 @@ public void start(final BaseCallback callback) { /** * Executes the delegation request against Auth0 API + * * @return the delegation response on success * @throws Auth0Exception when the delegation request fails */ diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index b11d5b8b..6b3949e5 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -177,7 +177,7 @@ public ParameterBuilder addAll(Map parameters) { * * @return itself */ - public ParameterBuilder clearAll() { + public ParameterBuilder clearAllA() { parameters.clear(); return this; } diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index a2b12842..f84403e3 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -52,7 +52,7 @@ public class SignUpRequest implements Request { * @return itself */ public SignUpRequest addSignUpParameters(Map parameters) { - signUpRequest.addParameters(parameters); + signUpRequest.getParameterBuilder().addAll(parameters); return this; } diff --git a/lib/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/internal/BaseRequest.java index c1ccd5d3..885f942d 100644 --- a/lib/src/main/java/com/auth0/internal/BaseRequest.java +++ b/lib/src/main/java/com/auth0/internal/BaseRequest.java @@ -27,6 +27,7 @@ import com.auth0.APIException; import com.auth0.Auth0Exception; import com.auth0.RequestBodyBuildException; +import com.auth0.authentication.ParameterBuilder; import com.auth0.callback.BaseCallback; import com.auth0.request.AuthorizableRequest; import com.auth0.request.ParameterizableRequest; @@ -47,12 +48,12 @@ abstract class BaseRequest implements ParameterizableRequest, AuthorizableRequest, Callback { private final Map headers; - private final Map parameters; protected final HttpUrl url; protected final OkHttpClient client; private final ObjectReader reader; private final ObjectReader errorReader; private final ObjectWriter writer; + private final ParameterBuilder builder; private BaseCallback callback; @@ -68,7 +69,7 @@ public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, Object this.writer = writer; this.callback = callback; this.headers = new HashMap<>(); - this.parameters = new HashMap<>(); + this.builder = ParameterBuilder.newEmptyBuilder(); } protected void setCallback(BaseCallback callback) { @@ -92,16 +93,12 @@ protected Request.Builder newBuilder() { return builder; } - protected Map getParameters() { - return parameters; - } - protected ObjectReader getReader() { return reader; } protected RequestBody buildBody() throws RequestBodyBuildException { - return JsonRequestBodyBuilder.createBody(parameters, writer); + return JsonRequestBodyBuilder.createBody(builder.asDictionary(), writer); } protected APIException parseUnsuccessfulResponse(Response response) { @@ -140,11 +137,8 @@ public AuthorizableRequest setBearer(String jwt) { } @Override - public ParameterizableRequest addParameters(Map parameters) { - if (parameters != null) { - this.parameters.putAll(parameters); - } - return this; + public ParameterBuilder getParameterBuilder() { + return builder; } @Override diff --git a/lib/src/main/java/com/auth0/request/ParameterizableRequest.java b/lib/src/main/java/com/auth0/request/ParameterizableRequest.java index fed5ee61..98c04526 100644 --- a/lib/src/main/java/com/auth0/request/ParameterizableRequest.java +++ b/lib/src/main/java/com/auth0/request/ParameterizableRequest.java @@ -24,24 +24,26 @@ package com.auth0.request; -import java.util.Map; +import com.auth0.authentication.ParameterBuilder; /** * Defines a request that can be configured (payload and headers) + * * @param */ public interface ParameterizableRequest extends Request { /** - * Adds additional parameters to send in the request - * @param parameters as a non-null dictionary - * @return itself + * Getter for this request ParameterBuilder. + * + * @return the associated ParameterBuilder instance */ - ParameterizableRequest addParameters(Map parameters); + ParameterBuilder getParameterBuilder(); /** * Adds an additional header for the request - * @param name of the header + * + * @param name of the header * @param value of the header * @return itself */ diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index c4b7f04f..f9ce96bd 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -25,14 +25,16 @@ package com.auth0.authentication; -import com.auth0.*; -import com.auth0.util.AuthenticationAPI; -import com.auth0.util.MockBaseCallback; +import com.auth0.Auth0; +import com.auth0.Auth0Exception; import com.auth0.authentication.result.Authentication; import com.auth0.authentication.result.DatabaseUser; import com.auth0.authentication.result.Delegation; import com.auth0.authentication.result.Token; import com.auth0.authentication.result.UserProfile; +import com.auth0.request.ParameterizableRequest; +import com.auth0.util.AuthenticationAPI; +import com.auth0.util.MockBaseCallback; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.mockwebserver.RecordedRequest; @@ -51,7 +53,12 @@ import static com.auth0.util.CallbackMatcher.hasNoPayloadOfType; import static com.auth0.util.CallbackMatcher.hasPayload; import static com.auth0.util.CallbackMatcher.hasPayloadOfType; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public class AuthenticationAPIClientTest { @@ -97,9 +104,10 @@ public void shouldLoginWithResourceOwner() throws Exception { .set("password", "notapassword") .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); - client.loginWithResourceOwner() - .addParameters(parameters) - .start(callback); + ParameterizableRequest roRequest = client.loginWithResourceOwner(); + roRequest.getParameterBuilder() + .addAll(parameters); + roRequest.start(callback); assertThat(callback, hasPayloadOfType(Token.class)); @@ -126,10 +134,9 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); - final Token token = client - .loginWithResourceOwner() - .addParameters(parameters) - .execute(); + ParameterizableRequest roRequest = client.loginWithResourceOwner(); + roRequest.getParameterBuilder().addAll(parameters); + final Token token = roRequest.execute(); assertThat(token, is(notNullValue())); @@ -155,9 +162,9 @@ public void shouldFailLoginWithResourceOwner() throws Exception { .set("username", "support@auth0.com") .set("password", "notapassword") .asDictionary(); - client.loginWithResourceOwner() - .addParameters(parameters) - .start(callback); + ParameterizableRequest roRequest = client.loginWithResourceOwner(); + roRequest.getParameterBuilder().addAll(parameters); + roRequest.start(callback); assertThat(callback, hasNoPayloadOfType(Token.class)); } @@ -176,9 +183,9 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { Exception exception = null; try { - client.loginWithResourceOwner() - .addParameters(parameters) - .execute(); + ParameterizableRequest request = client.loginWithResourceOwner(); + request.getParameterBuilder().addAll(parameters); + request.execute(); } catch (Auth0Exception e) { exception = e; } @@ -189,12 +196,12 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { @Test public void shouldLoginWithUserAndPassword() throws Exception { mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); final MockBaseCallback callback = new MockBaseCallback<>(); client.login("support@auth0.com", "voidpassword") - .start(callback); + .start(callback); assertThat(callback, hasPayloadOfType(Authentication.class)); } @@ -218,7 +225,7 @@ public void shouldFetchTokenInfo() throws Exception { final MockBaseCallback callback = new MockBaseCallback<>(); client.tokenInfo("ID_TOKEN") - .start(callback); + .start(callback); assertThat(callback, hasPayloadOfType(UserProfile.class)); @@ -686,7 +693,7 @@ public void shouldGetNewIdTokenWithIdTokenSync() throws Exception { public void shouldGetCustomizedDelegationRequestWithIdToken() throws Exception { mockAPI.willReturnNewIdToken(); - final MockBaseCallback> callback = new MockBaseCallback<>(); + final MockBaseCallback> callback = new MockBaseCallback<>(); client.delegationWithIdToken(ID_TOKEN, "custom_api_type") .setScope("custom_scope") .setTarget("custom_target") @@ -770,7 +777,7 @@ public void shouldGetNewIdTokenWithRefreshTokenSync() throws Exception { public void shouldGetCustomizedDelegationRequestWithRefreshToken() throws Exception { mockAPI.willReturnNewIdToken(); - final MockBaseCallback> callback = new MockBaseCallback<>(); + final MockBaseCallback> callback = new MockBaseCallback<>(); client.delegationWithRefreshToken(REFRESH_TOKEN, "custom_api_type") .setScope("custom_scope") .setTarget("custom_target") @@ -822,7 +829,8 @@ public void shouldUnlinkAccount() throws Exception { assertThat(request.getPath(), equalTo("/unlink")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("clientID", CLIENT_ID)); +// assertThat(body, hasEntry("clientID", CLIENT_ID)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); assertThat(body, hasEntry("user_id", "user id")); assertThat(body, hasEntry("access_token", "access token")); @@ -840,7 +848,8 @@ public void shouldUnlinkAccountSync() throws Exception { assertThat(request.getPath(), equalTo("/unlink")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("clientID", CLIENT_ID)); +// assertThat(body, hasEntry("clientID", CLIENT_ID)); + assertThat(body, hasEntry("client_id", CLIENT_ID)); assertThat(body, hasEntry("user_id", "user id")); assertThat(body, hasEntry("access_token", "access token")); } @@ -850,15 +859,15 @@ public void shouldStartPasswordless() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = new ParameterBuilder() - .clearAll() + final Map parameters = ParameterBuilder.newEmptyBuilder() .setConnection("email") .set("send", "code") .set("email", "support@auth0.com") .asDictionary(); - client.passwordless() - .addParameters(parameters) - .start(callback); + + ParameterizableRequest pwRequest = client.passwordless(); + pwRequest.getParameterBuilder().addAll(parameters); + pwRequest.start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/passwordless/start")); @@ -876,16 +885,15 @@ public void shouldStartPasswordless() throws Exception { public void shouldStartPasswordlessSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - final Map parameters = new ParameterBuilder() - .clearAll() + final Map parameters = ParameterBuilder.newEmptyBuilder() .setConnection("email") .set("send", "code") .set("email", "support@auth0.com") .asDictionary(); - client.passwordless() - .addParameters(parameters) - .execute(); + ParameterizableRequest pwRequest = client.passwordless(); + pwRequest.getParameterBuilder().addAll(parameters); + pwRequest.execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/passwordless/start")); @@ -1194,6 +1202,7 @@ public void shouldSendSMSLinkIOSSync() throws Exception { } private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { - return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() {}); + return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() { + }); } } \ No newline at end of file From defff6a56880b0515e8c64f100b08610186ef633 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 14:40:52 -0300 Subject: [PATCH 46/89] extract constants --- .../AuthenticationAPIClient.java | 52 ++++++++++++------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index a3b09cdc..080f39a2 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -57,6 +57,20 @@ public class AuthenticationAPIClient { private static final String REFRESH_TOKEN_KEY = "refresh_token"; private static final String PHONE_NUMBER_KEY = "phone_number"; + private static final String ACCESS_TOKEN_PATH = "access_token"; + private static final String SMS_CONNECTION = "sms"; + private static final String EMAIL_CONNECTION = "email"; + private static final String SIGN_UP_PATH = "signup"; + private static final String DB_CONNECTIONS_PATH = "dbconnections"; + private static final String CHANGE_PASSWORD_PATH = "change_password"; + private static final String UNLINK_PATH = "unlink"; + private static final String USER_ID_KEY = "user_id"; + private static final String DELEGATION_PATH = "delegation"; + private static final String PASSWORDLESS_PATH = "passwordless"; + private static final String START_PATH = "start"; + private static final String OAUTH_PATH = "oauth"; + private static final String RESOURCE_OWNER_PATH = "ro"; + private static final String TOKEN_INFO_PATH = "tokeninfo"; private final Auth0 auth0; private final OkHttpClient client; @@ -148,8 +162,8 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { */ public AuthenticationRequest loginWithOAuthAccessToken(String token, String connection) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("oauth") - .addPathSegment("access_token") + .addPathSegment(OAUTH_PATH) + .addPathSegment(ACCESS_TOKEN_PATH) .build(); Map parameters = ParameterBuilder.newBuilder() @@ -177,7 +191,7 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) .setClientId(getClientId()) - .setConnection("sms") + .setConnection(SMS_CONNECTION) .asDictionary(); return newAuthenticationRequest(parameters); } @@ -195,7 +209,7 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) .setClientId(getClientId()) - .setConnection("email") + .setConnection(EMAIL_CONNECTION) .asDictionary(); return newAuthenticationRequest(parameters); } @@ -222,8 +236,8 @@ public Request tokenInfo(String idToken) { */ public ParameterizableRequest createUser(String email, String password, String username) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("dbconnections") - .addPathSegment("signup") + .addPathSegment(DB_CONNECTIONS_PATH) + .addPathSegment(SIGN_UP_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class); @@ -284,8 +298,8 @@ public SignUpRequest signUp(String email, String password) { */ public ChangePasswordRequest changePassword(String email) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("dbconnections") - .addPathSegment("change_password") + .addPathSegment(DB_CONNECTIONS_PATH) + .addPathSegment(CHANGE_PASSWORD_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper); @@ -365,14 +379,14 @@ public DelegationRequest> delegationWithRefreshToken(String public Request unlink(String userId, String accessToken) { //TODO: Test this after removing .set("clientID", getClientId()) HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("unlink") + .addPathSegment(UNLINK_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper); request.getParameterBuilder() .setClientId(getClientId()) .setAccessToken(accessToken) - .set("user_id", userId); + .set(USER_ID_KEY, userId); return request; } @@ -388,7 +402,7 @@ public ParameterizableRequest passwordlessWithEmail(String email, Password request.getParameterBuilder() .set(EMAIL_KEY, email) .setSend(passwordlessType) - .setConnection("email"); + .setConnection(EMAIL_CONNECTION); return request; } @@ -404,7 +418,7 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass request.getParameterBuilder() .set(PHONE_NUMBER_KEY, phoneNumber) .setSend(passwordlessType) - .setConnection("sms"); + .setConnection(SMS_CONNECTION); return request; } @@ -416,7 +430,7 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass */ public ParameterizableRequest> delegation() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("delegation") + .addPathSegment(DELEGATION_PATH) .build(); ParameterizableRequest> request = factory.rawPOST(url, client, mapper); @@ -428,7 +442,7 @@ public ParameterizableRequest> delegation() { protected ParameterizableRequest delegation(Class clazz) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("delegation") + .addPathSegment(DELEGATION_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper, clazz); @@ -446,8 +460,8 @@ protected ParameterizableRequest delegation(Class clazz) { */ public ParameterizableRequest passwordless() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("passwordless") - .addPathSegment("start") + .addPathSegment(PASSWORDLESS_PATH) + .addPathSegment(START_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper); @@ -457,8 +471,8 @@ public ParameterizableRequest passwordless() { protected ParameterizableRequest loginWithResourceOwner() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("oauth") - .addPathSegment("ro") + .addPathSegment(OAUTH_PATH) + .addPathSegment(RESOURCE_OWNER_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper, Token.class); @@ -470,7 +484,7 @@ protected ParameterizableRequest loginWithResourceOwner() { private ParameterizableRequest profileRequest() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() - .addPathSegment("tokeninfo") + .addPathSegment(TOKEN_INFO_PATH) .build(); return factory.POST(url, client, mapper, UserProfile.class); From 650b99ee5b5a63af9a257e16b2cadc88ac436de9 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 14:57:46 -0300 Subject: [PATCH 47/89] provide an immutable copy of the parameters dictionary --- .../authentication/AuthenticationAPIClient.java | 11 +++++------ .../auth0/authentication/ParameterBuilder.java | 7 ++++--- .../authentication/ParameterBuilderTest.java | 16 ++++++++++++++-- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 080f39a2..9ff39cbd 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -49,23 +49,22 @@ */ public class AuthenticationAPIClient { + private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; + private static final String SMS_CONNECTION = "sms"; + private static final String EMAIL_CONNECTION = "email"; private static final String USERNAME_KEY = "username"; private static final String PASSWORD_KEY = "password"; - private static final String DEFAULT_DB_CONNECTION = "Username-Password-Authentication"; private static final String ID_TOKEN_KEY = "id_token"; private static final String EMAIL_KEY = "email"; private static final String REFRESH_TOKEN_KEY = "refresh_token"; - private static final String PHONE_NUMBER_KEY = "phone_number"; + private static final String USER_ID_KEY = "user_id"; + private static final String DELEGATION_PATH = "delegation"; private static final String ACCESS_TOKEN_PATH = "access_token"; - private static final String SMS_CONNECTION = "sms"; - private static final String EMAIL_CONNECTION = "email"; private static final String SIGN_UP_PATH = "signup"; private static final String DB_CONNECTIONS_PATH = "dbconnections"; private static final String CHANGE_PASSWORD_PATH = "change_password"; private static final String UNLINK_PATH = "unlink"; - private static final String USER_ID_KEY = "user_id"; - private static final String DELEGATION_PATH = "delegation"; private static final String PASSWORDLESS_PATH = "passwordless"; private static final String START_PATH = "start"; private static final String OAUTH_PATH = "oauth"; diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 6b3949e5..3411b318 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -26,6 +26,7 @@ import com.auth0.util.CheckHelper; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -177,7 +178,7 @@ public ParameterBuilder addAll(Map parameters) { * * @return itself */ - public ParameterBuilder clearAllA() { + public ParameterBuilder clearAll() { parameters.clear(); return this; } @@ -185,10 +186,10 @@ public ParameterBuilder clearAllA() { /** * Create a {@link Map} with all the parameters * - * @return a new map with the parameters + * @return an unmodifiable map with the parameters */ public Map asDictionary() { - return new HashMap<>(this.parameters); + return Collections.unmodifiableMap(new HashMap<>(this.parameters)); } /** diff --git a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java index 4d349e0b..e8421419 100644 --- a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java +++ b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java @@ -35,7 +35,9 @@ import java.util.HashMap; import java.util.Map; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; @@ -132,8 +134,18 @@ public void shouldDoNothingWhenAddingNullParameters() throws Exception { @Test public void shouldProvideADictionaryCopy() throws Exception { Map parameters = builder.setClientId(CLIENT_ID).asDictionary(); - parameters.put("key", "value"); - assertThat(builder.asDictionary(), not(hasEntry("key", "value"))); + builder.set("key", "value"); + assertThat(parameters, not(hasEntry("key", "value"))); + } + + @Test + public void shouldProvideAnImmutableDictionary() throws Exception { + Map parameters = builder.setClientId(CLIENT_ID).asDictionary(); + try { + parameters.put("key", "value"); + } catch (Exception e) { + assertThat(e.getClass().getName(), is(equalTo(UnsupportedOperationException.class.getName()))); + } } private static Matcher> hasEntry(String key, Object value) { From 234515962ac21b6527baf7de8452631ea1672f53 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 16:25:56 -0300 Subject: [PATCH 48/89] revert changes to the unlink method call --- .../com/auth0/authentication/AuthenticationAPIClient.java | 4 ++-- .../auth0/authentication/AuthenticationAPIClientTest.java | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 9ff39cbd..8fcf8cb9 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -59,6 +59,7 @@ public class AuthenticationAPIClient { private static final String REFRESH_TOKEN_KEY = "refresh_token"; private static final String PHONE_NUMBER_KEY = "phone_number"; private static final String USER_ID_KEY = "user_id"; + private static final String CLIENT_ID_KEY = "clientID"; private static final String DELEGATION_PATH = "delegation"; private static final String ACCESS_TOKEN_PATH = "access_token"; private static final String SIGN_UP_PATH = "signup"; @@ -376,15 +377,14 @@ public DelegationRequest> delegationWithRefreshToken(String * @return a request to start */ public Request unlink(String userId, String accessToken) { - //TODO: Test this after removing .set("clientID", getClientId()) HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(UNLINK_PATH) .build(); ParameterizableRequest request = factory.POST(url, client, mapper); request.getParameterBuilder() - .setClientId(getClientId()) .setAccessToken(accessToken) + .set(CLIENT_ID_KEY, getClientId()) .set(USER_ID_KEY, userId); return request; } diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index f9ce96bd..a56466b7 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -829,8 +829,7 @@ public void shouldUnlinkAccount() throws Exception { assertThat(request.getPath(), equalTo("/unlink")); Map body = bodyFromRequest(request); -// assertThat(body, hasEntry("clientID", CLIENT_ID)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("clientID", CLIENT_ID)); assertThat(body, hasEntry("user_id", "user id")); assertThat(body, hasEntry("access_token", "access token")); @@ -848,8 +847,7 @@ public void shouldUnlinkAccountSync() throws Exception { assertThat(request.getPath(), equalTo("/unlink")); Map body = bodyFromRequest(request); -// assertThat(body, hasEntry("clientID", CLIENT_ID)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); + assertThat(body, hasEntry("clientID", CLIENT_ID)); assertThat(body, hasEntry("user_id", "user id")); assertThat(body, hasEntry("access_token", "access token")); } From cda1656ec0bda6444d4979699927d298d9fb9c27 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 16:38:34 -0300 Subject: [PATCH 49/89] rename factory methods --- .../authentication/AuthenticationAPIClient.java | 8 ++++---- .../auth0/authentication/ParameterBuilder.java | 17 +++++------------ .../java/com/auth0/internal/BaseRequest.java | 2 +- .../AuthenticationAPIClientTest.java | 12 ++++++------ .../authentication/ParameterBuilderTest.java | 7 +++---- 5 files changed, 19 insertions(+), 27 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 8fcf8cb9..1850afd2 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -145,7 +145,7 @@ public void setDefaultDbConnection(String defaultDbConnection) { * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ public AuthenticationRequest login(String usernameOrEmail, String password) { - Map requestParameters = ParameterBuilder.newBuilder() + Map requestParameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, usernameOrEmail) .set(PASSWORD_KEY, password) .setGrantType(GRANT_TYPE_PASSWORD) @@ -166,7 +166,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .addPathSegment(ACCESS_TOKEN_PATH) .build(); - Map parameters = ParameterBuilder.newBuilder() + Map parameters = ParameterBuilder.newAuthenticationBuilder() .setClientId(getClientId()) .setConnection(connection) .setAccessToken(token) @@ -186,7 +186,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { - Map parameters = ParameterBuilder.newBuilder() + Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) @@ -204,7 +204,7 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ public AuthenticationRequest loginWithEmail(String email, String verificationCode) { - Map parameters = ParameterBuilder.newBuilder() + Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, email) .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 3411b318..23c0e9de 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -50,14 +50,6 @@ public class ParameterBuilder { private Map parameters; - /** - * Creates a new builder - */ - private ParameterBuilder() { - this.parameters = new HashMap<>(); - setScope(SCOPE_OFFLINE_ACCESS); - } - /** * Creates a new builder with default parameters * @@ -197,8 +189,9 @@ public Map asDictionary() { * * @return a new builder */ - public static ParameterBuilder newBuilder() { - return new ParameterBuilder(); + public static ParameterBuilder newAuthenticationBuilder() { + return newBuilder() + .setScope(SCOPE_OFFLINE_ACCESS); } /** @@ -206,8 +199,8 @@ public static ParameterBuilder newBuilder() { * * @return a new builder */ - public static ParameterBuilder newEmptyBuilder() { - return new ParameterBuilder(new HashMap()); + public static ParameterBuilder newBuilder() { + return newBuilder(new HashMap()); } /** diff --git a/lib/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/internal/BaseRequest.java index 885f942d..b11bc0be 100644 --- a/lib/src/main/java/com/auth0/internal/BaseRequest.java +++ b/lib/src/main/java/com/auth0/internal/BaseRequest.java @@ -69,7 +69,7 @@ public BaseRequest(HttpUrl url, OkHttpClient client, ObjectReader reader, Object this.writer = writer; this.callback = callback; this.headers = new HashMap<>(); - this.builder = ParameterBuilder.newEmptyBuilder(); + this.builder = ParameterBuilder.newBuilder(); } protected void setCallback(BaseCallback callback) { diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index a56466b7..1fbc8ce3 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -97,7 +97,7 @@ public void shouldLoginWithResourceOwner() throws Exception { mockAPI.willReturnSuccessfulLogin(); final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = ParameterBuilder.newBuilder() + final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection("DB") .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) .set("username", "support@auth0.com") @@ -126,7 +126,7 @@ public void shouldLoginWithResourceOwner() throws Exception { public void shouldLoginWithResourceOwnerSync() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final Map parameters = ParameterBuilder.newBuilder() + final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection("DB") .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) .set("username", "support@auth0.com") @@ -156,7 +156,7 @@ public void shouldFailLoginWithResourceOwner() throws Exception { mockAPI.willReturnFailedLogin(); final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = ParameterBuilder.newBuilder() + final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) .set("username", "support@auth0.com") @@ -174,7 +174,7 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { mockAPI.willReturnFailedLogin(); final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = ParameterBuilder.newBuilder() + final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) .set("username", "support@auth0.com") @@ -857,7 +857,7 @@ public void shouldStartPasswordless() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - final Map parameters = ParameterBuilder.newEmptyBuilder() + final Map parameters = ParameterBuilder.newBuilder() .setConnection("email") .set("send", "code") .set("email", "support@auth0.com") @@ -883,7 +883,7 @@ public void shouldStartPasswordless() throws Exception { public void shouldStartPasswordlessSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - final Map parameters = ParameterBuilder.newEmptyBuilder() + final Map parameters = ParameterBuilder.newBuilder() .setConnection("email") .set("send", "code") .set("email", "support@auth0.com") diff --git a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java index e8421419..f86b82bc 100644 --- a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java +++ b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java @@ -37,7 +37,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; @@ -56,17 +55,17 @@ public class ParameterBuilderTest { @Before public void setUp() throws Exception { - this.builder = ParameterBuilder.newBuilder(); + this.builder = ParameterBuilder.newAuthenticationBuilder(); } @Test public void shouldInstantiateWithNoArguments() throws Exception { - assertThat(ParameterBuilder.newBuilder(), is(notNullValue())); + assertThat(ParameterBuilder.newAuthenticationBuilder(), is(notNullValue())); } @Test public void shouldInstantiateWithDefaultScope() throws Exception { - assertThat(ParameterBuilder.newBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(ParameterBuilder.newAuthenticationBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); } @Test From c9f49e17cdbdf66897a36d94e3ebd5c3c753c11c Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 16:42:08 -0300 Subject: [PATCH 50/89] make public some authentication common constants --- .../authentication/AuthenticationAPIClient.java | 12 +++++------- .../com/auth0/authentication/ParameterBuilder.java | 2 ++ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 1850afd2..b4b236a6 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -54,9 +54,7 @@ public class AuthenticationAPIClient { private static final String EMAIL_CONNECTION = "email"; private static final String USERNAME_KEY = "username"; private static final String PASSWORD_KEY = "password"; - private static final String ID_TOKEN_KEY = "id_token"; private static final String EMAIL_KEY = "email"; - private static final String REFRESH_TOKEN_KEY = "refresh_token"; private static final String PHONE_NUMBER_KEY = "phone_number"; private static final String USER_ID_KEY = "user_id"; private static final String CLIENT_ID_KEY = "clientID"; @@ -222,7 +220,7 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod */ public Request tokenInfo(String idToken) { ParameterizableRequest request = profileRequest(); - request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); return request; } @@ -318,7 +316,7 @@ public ChangePasswordRequest changePassword(String email) { */ public DelegationRequest delegationWithIdToken(String idToken) { ParameterizableRequest request = delegation(Delegation.class); - request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); @@ -333,7 +331,7 @@ public DelegationRequest delegationWithIdToken(String idToken) { */ public DelegationRequest delegationWithRefreshToken(String refreshToken) { ParameterizableRequest request = delegation(Delegation.class); - request.getParameterBuilder().set(REFRESH_TOKEN_KEY, refreshToken); + request.getParameterBuilder().set(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); @@ -348,7 +346,7 @@ public DelegationRequest delegationWithRefreshToken(String refreshTo */ public DelegationRequest> delegationWithIdToken(String idToken, String apiType) { ParameterizableRequest> request = delegation(); - request.getParameterBuilder().set(ID_TOKEN_KEY, idToken); + request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); return new DelegationRequest<>(request) .setApiType(apiType); @@ -364,7 +362,7 @@ public DelegationRequest> delegationWithIdToken(String idTok */ public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { ParameterizableRequest> request = delegation(); - request.getParameterBuilder().set(REFRESH_TOKEN_KEY, refreshToken); + request.getParameterBuilder().set(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); return new DelegationRequest<>(request).setApiType(apiType); } diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 23c0e9de..f6e8393e 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -39,6 +39,8 @@ public class ParameterBuilder { public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public static final String SCOPE_OPENID = "openid"; public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; + public static final String ID_TOKEN_KEY = "id_token"; + public static final String REFRESH_TOKEN_KEY = "refresh_token"; private static final String ACCESS_TOKEN_KEY = "access_token"; private static final String CONNECTION_KEY = "connection"; From b9530ba9ae08b19b166ecaa61628d538f80b0a5d Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 10 Feb 2016 17:06:43 -0300 Subject: [PATCH 51/89] small fixes --- .../com/auth0/authentication/AuthenticationAPIClient.java | 5 ++--- lib/src/main/java/com/auth0/internal/BaseRequest.java | 8 -------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index b4b236a6..d0e8ca0d 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -485,14 +485,13 @@ private ParameterizableRequest profileRequest() { .build(); return factory.POST(url, client, mapper, UserProfile.class); - } private AuthenticationRequest newAuthenticationRequest(Map parameters) { final ParameterizableRequest credentialsRequest = loginWithResourceOwner(); - credentialsRequest.getParameterBuilder().addAll(parameters); final ParameterizableRequest profileRequest = profileRequest(); - return new AuthenticationRequest(credentialsRequest, profileRequest); + return new AuthenticationRequest(credentialsRequest, profileRequest) + .addParameters(parameters); } } diff --git a/lib/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/internal/BaseRequest.java index b11bc0be..41f19d69 100644 --- a/lib/src/main/java/com/auth0/internal/BaseRequest.java +++ b/lib/src/main/java/com/auth0/internal/BaseRequest.java @@ -111,14 +111,6 @@ protected APIException parseUnsuccessfulResponse(Response response) { } } - private static abstract class CallbackTask implements Runnable { - protected final BaseCallback callback; - - protected CallbackTask(BaseCallback callback) { - this.callback = callback; - } - } - @Override public void onFailure(Request request, IOException e) { postOnFailure(new Auth0Exception("Failed to execute request to " + url.toString(), e)); From 97e4a98333d95cdff3f2447b6ab0217fce920ddf Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 15 Mar 2016 20:09:47 -0300 Subject: [PATCH 52/89] Decouple authentication from logins Now only return token instead of token and profile. Addded a method to chain get profile after a successful authentication --- .../AuthenticationAPIClient.java | 42 +++--- .../auth0/authentication/SignUpRequest.java | 25 ++-- .../AuthenticationAPIClientTest.java | 125 ++++++++++-------- 3 files changed, 105 insertions(+), 87 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index d0e8ca0d..45b4bb8b 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -69,6 +69,7 @@ public class AuthenticationAPIClient { private static final String OAUTH_PATH = "oauth"; private static final String RESOURCE_OWNER_PATH = "ro"; private static final String TOKEN_INFO_PATH = "tokeninfo"; + private static final String ID_TOKEN = "id_token"; private final Auth0 auth0; private final OkHttpClient client; @@ -142,13 +143,13 @@ public void setDefaultDbConnection(String defaultDbConnection) { * @param password of the user * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public AuthenticationRequest login(String usernameOrEmail, String password) { + public ParameterizableRequest login(String usernameOrEmail, String password) { Map requestParameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, usernameOrEmail) .set(PASSWORD_KEY, password) .setGrantType(GRANT_TYPE_PASSWORD) .asDictionary(); - return newAuthenticationRequest(requestParameters); + return loginWithResourceOwner(requestParameters); } /** @@ -158,7 +159,7 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { * @param connection that will be used to authenticate the user, e.g. 'facebook' * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public AuthenticationRequest loginWithOAuthAccessToken(String token, String connection) { + public ParameterizableRequest loginWithOAuthAccessToken(String token, String connection) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(ACCESS_TOKEN_PATH) @@ -170,10 +171,9 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn .setAccessToken(token) .asDictionary(); - final ParameterizableRequest profileRequest = profileRequest(); ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Token.class); credentialsRequest.getParameterBuilder().addAll(parameters); - return new AuthenticationRequest(credentialsRequest, profileRequest); + return credentialsRequest; } /** @@ -183,7 +183,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn * @param verificationCode sent by Auth0 via SMS * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { + public ParameterizableRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) @@ -191,7 +191,7 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver .setClientId(getClientId()) .setConnection(SMS_CONNECTION) .asDictionary(); - return newAuthenticationRequest(parameters); + return loginWithResourceOwner(parameters); } /** @@ -201,7 +201,7 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver * @param verificationCode sent by Auth0 via Email * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ - public AuthenticationRequest loginWithEmail(String email, String verificationCode) { + public ParameterizableRequest loginWithEmail(String email, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, email) .set(PASSWORD_KEY, verificationCode) @@ -209,7 +209,7 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod .setClientId(getClientId()) .setConnection(EMAIL_CONNECTION) .asDictionary(); - return newAuthenticationRequest(parameters); + return loginWithResourceOwner(parameters); } /** @@ -269,8 +269,8 @@ public ParameterizableRequest createUser(String email, String pass * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} */ public SignUpRequest signUp(String email, String password, String username) { - ParameterizableRequest createUserRequest = createUser(email, password, username); - AuthenticationRequest authenticationRequest = login(email, password); + final ParameterizableRequest createUserRequest = createUser(email, password, username); + final ParameterizableRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -284,7 +284,7 @@ public SignUpRequest signUp(String email, String password, String username) { */ public SignUpRequest signUp(String email, String password) { ParameterizableRequest createUserRequest = createUser(email, password); - AuthenticationRequest authenticationRequest = login(email, password); + final ParameterizableRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -466,7 +466,12 @@ public ParameterizableRequest passwordless() { return request; } - protected ParameterizableRequest loginWithResourceOwner() { + public AuthenticationRequest getProfileAfter(ParameterizableRequest loginRequest) { + final ParameterizableRequest profileRequest = profileRequest(); + return new AuthenticationRequest(loginRequest, profileRequest); + } + + protected ParameterizableRequest loginWithResourceOwner(Map parameters) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(RESOURCE_OWNER_PATH) @@ -475,7 +480,8 @@ protected ParameterizableRequest loginWithResourceOwner() { ParameterizableRequest request = factory.POST(url, client, mapper, Token.class); request.getParameterBuilder() .setClientId(getClientId()) - .setConnection(defaultDbConnection); + .setConnection(defaultDbConnection) + .addAll(parameters); return request; } @@ -486,12 +492,4 @@ private ParameterizableRequest profileRequest() { return factory.POST(url, client, mapper, UserProfile.class); } - - private AuthenticationRequest newAuthenticationRequest(Map parameters) { - final ParameterizableRequest credentialsRequest = loginWithResourceOwner(); - final ParameterizableRequest profileRequest = profileRequest(); - - return new AuthenticationRequest(credentialsRequest, profileRequest) - .addParameters(parameters); - } } diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index f84403e3..085840c3 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -25,6 +25,7 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; +import com.auth0.authentication.result.Token; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; import com.auth0.callback.BaseCallback; @@ -34,14 +35,14 @@ import java.util.Map; /** - * Represent a request to create a user + log in + fetch user profile. + * Represent a request to create a user + log in */ -public class SignUpRequest implements Request { +public class SignUpRequest implements Request { private final ParameterizableRequest signUpRequest; - private final AuthenticationRequest authenticationRequest; + private final ParameterizableRequest authenticationRequest; - SignUpRequest(ParameterizableRequest signUpRequest, AuthenticationRequest authenticationRequest) { + SignUpRequest(ParameterizableRequest signUpRequest, ParameterizableRequest authenticationRequest) { this.signUpRequest = signUpRequest; this.authenticationRequest = authenticationRequest; } @@ -62,7 +63,9 @@ public SignUpRequest addSignUpParameters(Map parameters) { * @return itself */ public SignUpRequest addAuthenticationParameters(Map parameters) { - authenticationRequest.addParameters(parameters); + authenticationRequest + .getParameterBuilder() + .addAll(parameters); return this; } @@ -72,7 +75,9 @@ public SignUpRequest addAuthenticationParameters(Map parameters) * @return itself */ public SignUpRequest setScope(String scope) { - authenticationRequest.setScope(scope); + authenticationRequest + .getParameterBuilder() + .setScope(scope); return this; } @@ -82,7 +87,9 @@ public SignUpRequest setScope(String scope) { * @return itself */ public SignUpRequest setConnection(String connection) { - authenticationRequest.setConnection(connection); + authenticationRequest + .getParameterBuilder() + .setConnection(connection); return this; } @@ -91,7 +98,7 @@ public SignUpRequest setConnection(String connection) { * @param callback called on either success or failure. */ @Override - public void start(final BaseCallback callback) { + public void start(final BaseCallback callback) { signUpRequest.start(new BaseCallback() { @Override public void onSuccess(final DatabaseUser user) { @@ -112,7 +119,7 @@ public void onFailure(Auth0Exception error) { * @throws Auth0Exception on failure */ @Override - public Authentication execute() throws Auth0Exception { + public Token execute() throws Auth0Exception { signUpRequest.execute(); return authenticationRequest.execute(); } diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 1fbc8ce3..fcbbc37d 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -32,6 +32,7 @@ import com.auth0.authentication.result.Delegation; import com.auth0.authentication.result.Token; import com.auth0.authentication.result.UserProfile; +import com.auth0.callback.BaseCallback; import com.auth0.request.ParameterizableRequest; import com.auth0.util.AuthenticationAPI; import com.auth0.util.MockBaseCallback; @@ -104,10 +105,9 @@ public void shouldLoginWithResourceOwner() throws Exception { .set("password", "notapassword") .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); - ParameterizableRequest roRequest = client.loginWithResourceOwner(); - roRequest.getParameterBuilder() - .addAll(parameters); - roRequest.start(callback); + client + .loginWithResourceOwner(parameters) + .start(callback); assertThat(callback, hasPayloadOfType(Token.class)); @@ -134,9 +134,9 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); - ParameterizableRequest roRequest = client.loginWithResourceOwner(); - roRequest.getParameterBuilder().addAll(parameters); - final Token token = roRequest.execute(); + final Token token = client + .loginWithResourceOwner(parameters) + .execute(); assertThat(token, is(notNullValue())); @@ -162,9 +162,9 @@ public void shouldFailLoginWithResourceOwner() throws Exception { .set("username", "support@auth0.com") .set("password", "notapassword") .asDictionary(); - ParameterizableRequest roRequest = client.loginWithResourceOwner(); - roRequest.getParameterBuilder().addAll(parameters); - roRequest.start(callback); + client + .loginWithResourceOwner(parameters) + .start(callback); assertThat(callback, hasNoPayloadOfType(Token.class)); } @@ -183,9 +183,7 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { Exception exception = null; try { - ParameterizableRequest request = client.loginWithResourceOwner(); - request.getParameterBuilder().addAll(parameters); - request.execute(); + client.loginWithResourceOwner(parameters).execute(); } catch (Auth0Exception e) { exception = e; } @@ -196,27 +194,27 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { @Test public void shouldLoginWithUserAndPassword() throws Exception { mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); + .willReturnSuccessfulLogin(); + + final MockBaseCallback callback = new MockBaseCallback<>(); - client.login("support@auth0.com", "voidpassword") + client + .login("support@auth0.com", "voidpassword") .start(callback); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test public void shouldLoginWithUserAndPasswordSync() throws Exception { mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + .willReturnSuccessfulLogin(); - final Authentication authentication = client + final Token token= client .login("support@auth0.com", "voidpassword") .execute(); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test @@ -250,10 +248,9 @@ public void shouldFetchTokenInfoSync() throws Exception { @Test public void shouldLoginWithOAuthAccessToken() throws Exception { mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + .willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithOAuthAccessToken("fbtoken", "facebook") .start(callback); @@ -265,16 +262,14 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { assertThat(body, hasEntry("access_token", "fbtoken")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test public void shouldLoginWithOAuthAccessTokenSync() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + mockAPI.willReturnSuccessfulLogin(); - final Authentication authentication = client + final Token token = client .loginWithOAuthAccessToken("fbtoken", "facebook") .execute(); @@ -286,16 +281,14 @@ public void shouldLoginWithOAuthAccessTokenSync() throws Exception { assertThat(body, hasEntry("access_token", "fbtoken")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test public void shouldLoginWithPhoneNumber() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithPhoneNumber("+10101010101", "1234") .start(callback); @@ -308,16 +301,14 @@ public void shouldLoginWithPhoneNumber() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test public void shouldLoginWithPhoneNumberSync() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + mockAPI.willReturnSuccessfulLogin(); - final Authentication authentication = client + final Token token = client .loginWithPhoneNumber("+10101010101", "1234") .execute(); @@ -330,16 +321,14 @@ public void shouldLoginWithPhoneNumberSync() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test public void shouldLoginWithEmailOnly() throws Exception { - mockAPI - .willReturnSuccessfulLogin() - .willReturnTokenInfo(); + mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithEmail("support@auth0.com", "1234") .start(callback); @@ -352,7 +341,7 @@ public void shouldLoginWithEmailOnly() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test @@ -361,7 +350,7 @@ public void shouldLoginWithEmailOnlySync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Authentication authentication = client + final Token token = client .loginWithEmail("support@auth0.com", "1234") .execute(); @@ -374,7 +363,7 @@ public void shouldLoginWithEmailOnlySync() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test @@ -459,7 +448,7 @@ public void shouldSignUpUser() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123", "support") .start(callback); @@ -471,7 +460,7 @@ public void shouldSignUpUser() throws Exception { assertThat(body, hasEntry("username", "support")); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test @@ -480,7 +469,7 @@ public void shouldSignUpUserSync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Authentication authentication = client + final Token token = client .signUp("support@auth0.com", "123123123", "support") .execute(); @@ -492,7 +481,7 @@ public void shouldSignUpUserSync() throws Exception { assertThat(body, hasEntry("username", "support")); assertThat(body, hasEntry("password", "123123123")); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test @@ -501,7 +490,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123") .start(callback); @@ -513,7 +502,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { assertThat(body, not(hasEntry("username", "support"))); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasPayloadOfType(Authentication.class)); + assertThat(callback, hasPayloadOfType(Token.class)); } @Test @@ -522,7 +511,7 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Authentication authentication = client + final Token token = client .signUp("support@auth0.com", "123123123") .execute(); @@ -534,7 +523,7 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception { assertThat(body, hasEntry("username", null)); assertThat(body, hasEntry("password", "123123123")); - assertThat(authentication, is(notNullValue())); + assertThat(token, is(notNullValue())); } @Test @@ -1199,6 +1188,30 @@ public void shouldSendSMSLinkIOSSync() throws Exception { assertThat(body, hasEntry("connection", "sms")); } + @Test + public void shouldFetchProfileAfterLoginRequest() throws Exception { + mockAPI + .willReturnSuccessfulLogin() + .willReturnTokenInfo(); + + MockBaseCallback callback = new MockBaseCallback<>(); + client.getProfileAfter(client.login("support@auth0.com", "voidpassword")) + .start(callback); + + final RecordedRequest firstRequest = mockAPI.takeRequest(); + assertThat(firstRequest.getPath(), equalTo("/oauth/ro")); + + Map body = bodyFromRequest(firstRequest); + assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("password", "voidpassword")); + + final RecordedRequest secondRequest = mockAPI.takeRequest(); + assertThat(secondRequest.getPath(), equalTo("/tokeninfo")); + + assertThat(callback, hasPayloadOfType(Authentication.class)); + + } + private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException { return new ObjectMapper().readValue(request.getBody().inputStream(), new TypeReference>() { }); From 3625468de19d4cb3a11cd6b12bb7cdbe55a5debc Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 15 Mar 2016 20:36:52 -0300 Subject: [PATCH 53/89] Rename Token to Credentials --- .../AuthenticationAPIClient.java | 53 ++++++++------ .../authentication/AuthenticationRequest.java | 20 ++--- .../auth0/authentication/SignUpRequest.java | 13 ++-- .../authentication/result/Authentication.java | 15 ++-- .../result/{Token.java => Credentials.java} | 31 ++++---- .../authentication/result/DatabaseUser.java | 5 +- .../authentication/result/Delegation.java | 5 +- .../authentication/result/UserProfile.java | 12 ++- .../AuthenticationAPIClientTest.java | 73 +++++++++---------- 9 files changed, 117 insertions(+), 110 deletions(-) rename lib/src/main/java/com/auth0/authentication/result/{Token.java => Credentials.java} (67%) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 45b4bb8b..af694819 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -25,9 +25,9 @@ package com.auth0.authentication; import com.auth0.Auth0; +import com.auth0.authentication.result.Credentials; import com.auth0.authentication.result.DatabaseUser; import com.auth0.authentication.result.Delegation; -import com.auth0.authentication.result.Token; import com.auth0.authentication.result.UserProfile; import com.auth0.internal.RequestFactory; import com.auth0.request.ParameterizableRequest; @@ -69,7 +69,6 @@ public class AuthenticationAPIClient { private static final String OAUTH_PATH = "oauth"; private static final String RESOURCE_OWNER_PATH = "ro"; private static final String TOKEN_INFO_PATH = "tokeninfo"; - private static final String ID_TOKEN = "id_token"; private final Auth0 auth0; private final OkHttpClient client; @@ -137,13 +136,13 @@ public void setDefaultDbConnection(String defaultDbConnection) { } /** - * Log in a user with email/username and password using a DB connection and fetch it's profile from Auth0 + * Log in a user with email/username and password using a DB connection * * @param usernameOrEmail of the user depending of the type of DB connection * @param password of the user - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest login(String usernameOrEmail, String password) { + public ParameterizableRequest login(String usernameOrEmail, String password) { Map requestParameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, usernameOrEmail) .set(PASSWORD_KEY, password) @@ -157,9 +156,9 @@ public ParameterizableRequest login(String usernameOrEmail, String passwo * * @param token obtained from the IdP * @param connection that will be used to authenticate the user, e.g. 'facebook' - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithOAuthAccessToken(String token, String connection) { + public ParameterizableRequest loginWithOAuthAccessToken(String token, String connection) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(ACCESS_TOKEN_PATH) @@ -171,7 +170,7 @@ public ParameterizableRequest loginWithOAuthAccessToken(String token, Str .setAccessToken(token) .asDictionary(); - ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Token.class); + ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Credentials.class); credentialsRequest.getParameterBuilder().addAll(parameters); return credentialsRequest; } @@ -181,9 +180,9 @@ public ParameterizableRequest loginWithOAuthAccessToken(String token, Str * * @param phoneNumber where the user received the verification code * @param verificationCode sent by Auth0 via SMS - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { + public ParameterizableRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) @@ -199,9 +198,9 @@ public ParameterizableRequest loginWithPhoneNumber(String phoneNumber, St * * @param email where the user received the verification code * @param verificationCode sent by Auth0 via Email - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithEmail(String email, String verificationCode) { + public ParameterizableRequest loginWithEmail(String email, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, email) .set(PASSWORD_KEY, verificationCode) @@ -261,40 +260,40 @@ public ParameterizableRequest createUser(String email, String pass /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint - * and then logs in and fetches it's user profile + * and then logs in * * @param email of the user and must be non null * @param password of the user and must be non null * @param username of the user and must be non null - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ public SignUpRequest signUp(String email, String password, String username) { final ParameterizableRequest createUserRequest = createUser(email, password, username); - final ParameterizableRequest authenticationRequest = login(email, password); + final ParameterizableRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint - * and then logs in and fetches it's user profile + * and then logs in * * @param email of the user and must be non null * @param password of the user and must be non null - * @return a request to configure and start that will yield {@link Token} and {@link UserProfile} + * @return a request to configure and start that will yield {@link Credentials} */ public SignUpRequest signUp(String email, String password) { ParameterizableRequest createUserRequest = createUser(email, password); - final ParameterizableRequest authenticationRequest = login(email, password); + final ParameterizableRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } /** - * Perform a change password request using '/dbconnections/change_password' + * Request a change password using '/dbconnections/change_password' * - * @param email of the user that changes the password. It's also where the confirmation email will be sent + * @param email of the user that changes the password. It's also where the email will be sent with the link to perform the change password. * @return a request to configure and start */ - public ChangePasswordRequest changePassword(String email) { + public ChangePasswordRequest requestChangePassword(String email) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(DB_CONNECTIONS_PATH) .addPathSegment(CHANGE_PASSWORD_PATH) @@ -466,18 +465,24 @@ public ParameterizableRequest passwordless() { return request; } - public AuthenticationRequest getProfileAfter(ParameterizableRequest loginRequest) { + /** + * Fetch the user's profile after it's authenticated by a login request. + * If the login request fails, the returned request will fail + * @param loginRequest that will authenticate a user with Auth0 and return a {@see Credentials} + * @return a {@see AuthenticationRequest} that first logins and the fetches the profile + */ + public AuthenticationRequest getProfileAfter(ParameterizableRequest loginRequest) { final ParameterizableRequest profileRequest = profileRequest(); return new AuthenticationRequest(loginRequest, profileRequest); } - protected ParameterizableRequest loginWithResourceOwner(Map parameters) { + protected ParameterizableRequest loginWithResourceOwner(Map parameters) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(RESOURCE_OWNER_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper, Token.class); + ParameterizableRequest request = factory.POST(url, client, mapper, Credentials.class); request.getParameterBuilder() .setClientId(getClientId()) .setConnection(defaultDbConnection) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java index fabaa385..2f67cb3c 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -25,10 +25,10 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; +import com.auth0.authentication.result.Credentials; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; import com.auth0.callback.BaseCallback; -import com.auth0.authentication.result.Token; import com.auth0.authentication.result.UserProfile; import com.auth0.authentication.result.Authentication; @@ -41,10 +41,10 @@ public class AuthenticationRequest implements Request { private static final String ID_TOKEN_KEY = "id_token"; - private final ParameterizableRequest credentialsRequest; + private final ParameterizableRequest credentialsRequest; private final ParameterizableRequest tokenInfoRequest; - AuthenticationRequest(ParameterizableRequest credentialsRequest, ParameterizableRequest tokenInfoRequest) { + AuthenticationRequest(ParameterizableRequest credentialsRequest, ParameterizableRequest tokenInfoRequest) { this.credentialsRequest = credentialsRequest; this.tokenInfoRequest = tokenInfoRequest; } @@ -89,17 +89,17 @@ public AuthenticationRequest setConnection(String connection) { */ @Override public void start(final BaseCallback callback) { - credentialsRequest.start(new BaseCallback() { + credentialsRequest.start(new BaseCallback() { @Override - public void onSuccess(final Token token) { + public void onSuccess(final Credentials credentials) { tokenInfoRequest .getParameterBuilder() - .set(ID_TOKEN_KEY, token.getIdToken()); + .set(ID_TOKEN_KEY, credentials.getIdToken()); tokenInfoRequest .start(new BaseCallback() { @Override public void onSuccess(UserProfile profile) { - callback.onSuccess(new Authentication(profile, token)); + callback.onSuccess(new Authentication(profile, credentials)); } @Override @@ -124,10 +124,10 @@ public void onFailure(Auth0Exception error) { */ @Override public Authentication execute() throws Auth0Exception { - Token token = credentialsRequest.execute(); - tokenInfoRequest.getParameterBuilder().set(ID_TOKEN_KEY, token.getIdToken()); + Credentials credentials = credentialsRequest.execute(); + tokenInfoRequest.getParameterBuilder().set(ID_TOKEN_KEY, credentials.getIdToken()); UserProfile profile = tokenInfoRequest .execute(); - return new Authentication(profile, token); + return new Authentication(profile, credentials); } } diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index 085840c3..e348bfa2 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -25,24 +25,23 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; -import com.auth0.authentication.result.Token; +import com.auth0.authentication.result.Credentials; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; import com.auth0.callback.BaseCallback; import com.auth0.authentication.result.DatabaseUser; -import com.auth0.authentication.result.Authentication; import java.util.Map; /** * Represent a request to create a user + log in */ -public class SignUpRequest implements Request { +public class SignUpRequest implements Request { private final ParameterizableRequest signUpRequest; - private final ParameterizableRequest authenticationRequest; + private final ParameterizableRequest authenticationRequest; - SignUpRequest(ParameterizableRequest signUpRequest, ParameterizableRequest authenticationRequest) { + SignUpRequest(ParameterizableRequest signUpRequest, ParameterizableRequest authenticationRequest) { this.signUpRequest = signUpRequest; this.authenticationRequest = authenticationRequest; } @@ -98,7 +97,7 @@ public SignUpRequest setConnection(String connection) { * @param callback called on either success or failure. */ @Override - public void start(final BaseCallback callback) { + public void start(final BaseCallback callback) { signUpRequest.start(new BaseCallback() { @Override public void onSuccess(final DatabaseUser user) { @@ -119,7 +118,7 @@ public void onFailure(Auth0Exception error) { * @throws Auth0Exception on failure */ @Override - public Token execute() throws Auth0Exception { + public Credentials execute() throws Auth0Exception { signUpRequest.execute(); return authenticationRequest.execute(); } diff --git a/lib/src/main/java/com/auth0/authentication/result/Authentication.java b/lib/src/main/java/com/auth0/authentication/result/Authentication.java index 6e35f35b..58e2575b 100644 --- a/lib/src/main/java/com/auth0/authentication/result/Authentication.java +++ b/lib/src/main/java/com/auth0/authentication/result/Authentication.java @@ -29,25 +29,26 @@ /** * The result of a successful authentication against Auth0 - * Contains the logged in user's {@link Token} and {@link UserProfile} + * Contains the logged in user's {@link Credentials} and {@link UserProfile}. + * @see com.auth0.authentication.AuthenticationAPIClient#getProfileAfter(com.auth0.request.ParameterizableRequest) */ public class Authentication { private final UserProfile profile; - private final Token token; + private final Credentials credentials; - public Authentication(UserProfile profile, Token token) { + public Authentication(UserProfile profile, Credentials credentials) { checkArgument(profile != null, "profile must be non-null"); - checkArgument(token != null, "token must be non-null"); + checkArgument(credentials != null, "credentials must be non-null"); this.profile = profile; - this.token = token; + this.credentials = credentials; } public UserProfile getProfile() { return profile; } - public Token getToken() { - return token; + public Credentials getCredentials() { + return credentials; } } diff --git a/lib/src/main/java/com/auth0/authentication/result/Token.java b/lib/src/main/java/com/auth0/authentication/result/Credentials.java similarity index 67% rename from lib/src/main/java/com/auth0/authentication/result/Token.java rename to lib/src/main/java/com/auth0/authentication/result/Credentials.java index 1c0bb909..b3584e53 100644 --- a/lib/src/main/java/com/auth0/authentication/result/Token.java +++ b/lib/src/main/java/com/auth0/authentication/result/Credentials.java @@ -28,31 +28,34 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * Class that holds a user's token information. + * Holds the user's credentials returned by Auth0. + *
    + *
  • idToken: Identity Token with user information
  • + *
  • accessToken: Access Token for Auth0 API
  • + *
  • refreshToken: Refresh Token that can be used to request new tokens without signing in again
  • + *
*/ @JsonIgnoreProperties(ignoreUnknown = true) -public class Token { +public class Credentials { protected String idToken; protected String accessToken; protected String type; protected String refreshToken; - protected Token(Token token) { - idToken = token.idToken; - accessToken = token.accessToken; - type = token.type; - refreshToken = token.refreshToken; + protected Credentials(Credentials credentials) { + idToken = credentials.idToken; + accessToken = credentials.accessToken; + type = credentials.type; + refreshToken = credentials.refreshToken; } - protected Token() { + protected Credentials() { } - } - - public Token(@JsonProperty(value = "id_token", required = true) String idToken, - @JsonProperty(value = "access_token") String accessToken, - @JsonProperty(value = "token_type") String type, - @JsonProperty(value = "refresh_token") String refreshToken) { + public Credentials(@JsonProperty(value = "id_token", required = true) String idToken, + @JsonProperty(value = "access_token") String accessToken, + @JsonProperty(value = "token_type") String type, + @JsonProperty(value = "refresh_token") String refreshToken) { this.idToken = idToken; this.accessToken = accessToken; this.type = type; diff --git a/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java b/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java index 2edeca47..ad1fe1bc 100644 --- a/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java +++ b/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java @@ -28,7 +28,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * Value holder for Database Sign Up operation + * Auth0 user created in a Database connection. + * + * @see com.auth0.authentication.AuthenticationAPIClient#signUp(String, String) + * @see com.auth0.authentication.AuthenticationAPIClient#signUp(String, String, String) */ @JsonIgnoreProperties(ignoreUnknown = true) public class DatabaseUser { diff --git a/lib/src/main/java/com/auth0/authentication/result/Delegation.java b/lib/src/main/java/com/auth0/authentication/result/Delegation.java index 1f309491..feb06bdf 100644 --- a/lib/src/main/java/com/auth0/authentication/result/Delegation.java +++ b/lib/src/main/java/com/auth0/authentication/result/Delegation.java @@ -31,8 +31,7 @@ import static com.auth0.util.CheckHelper.checkArgument; /** - * The result of a successful delegation to an Auth0 app. - * Contains a new Auth0 'id_token' to be used on the 'target' app + * The result of a successful delegation to an Auth0 application that contains a new Auth0 'id_token' * See delegation docs */ @JsonIgnoreProperties(ignoreUnknown = true) @@ -54,7 +53,7 @@ public Delegation(@JsonProperty(value = "id_token") String idToken, } /** - * Id token + * Identity Token * @return the 'id_token' value */ public String getIdToken() { diff --git a/lib/src/main/java/com/auth0/authentication/result/UserProfile.java b/lib/src/main/java/com/auth0/authentication/result/UserProfile.java index 5d9a4faf..e1248440 100644 --- a/lib/src/main/java/com/auth0/authentication/result/UserProfile.java +++ b/lib/src/main/java/com/auth0/authentication/result/UserProfile.java @@ -40,7 +40,7 @@ import java.util.TimeZone; /** - * Class that holds the information of a user's profile + * Class that holds the information of a user's profile in Auth0 */ @JsonIgnoreProperties(ignoreUnknown = true) public class UserProfile implements Serializable { @@ -64,9 +64,7 @@ protected UserProfile(UserProfile userProfile) { identities = userProfile.identities; } - protected UserProfile() { - - } + protected UserProfile() { } @JsonCreator @SuppressWarnings("unchecked") @@ -117,9 +115,9 @@ public Date getCreatedAt() { } /** - * Returns extra information of the profile. + * Returns extra information of the profile that is not part of the normalized profile * - * @return + * @return a map with user's extra information found in the profile */ public Map getExtraInfo() { return new HashMap<>(extraInfo); @@ -128,7 +126,7 @@ public Map getExtraInfo() { /** * List of the identities from a Identity Provider associated to the user. * - * @return + * @return a list of identity provider information. */ public List getIdentities() { return identities; diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index fcbbc37d..7011d59f 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -28,11 +28,10 @@ import com.auth0.Auth0; import com.auth0.Auth0Exception; import com.auth0.authentication.result.Authentication; +import com.auth0.authentication.result.Credentials; import com.auth0.authentication.result.DatabaseUser; import com.auth0.authentication.result.Delegation; -import com.auth0.authentication.result.Token; import com.auth0.authentication.result.UserProfile; -import com.auth0.callback.BaseCallback; import com.auth0.request.ParameterizableRequest; import com.auth0.util.AuthenticationAPI; import com.auth0.util.MockBaseCallback; @@ -96,7 +95,7 @@ public void shouldCreateClientWithAccountInfo() throws Exception { @Test public void shouldLoginWithResourceOwner() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection("DB") @@ -109,7 +108,7 @@ public void shouldLoginWithResourceOwner() throws Exception { .loginWithResourceOwner(parameters) .start(callback); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/oauth/ro")); @@ -134,11 +133,11 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); - final Token token = client + final Credentials credentials = client .loginWithResourceOwner(parameters) .execute(); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/oauth/ro")); @@ -154,7 +153,7 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { @Test public void shouldFailLoginWithResourceOwner() throws Exception { mockAPI.willReturnFailedLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) @@ -166,13 +165,13 @@ public void shouldFailLoginWithResourceOwner() throws Exception { .loginWithResourceOwner(parameters) .start(callback); - assertThat(callback, hasNoPayloadOfType(Token.class)); + assertThat(callback, hasNoPayloadOfType(Credentials.class)); } @Test public void shouldFailLoginWithResourceOwnerSync() throws Exception { mockAPI.willReturnFailedLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) @@ -196,13 +195,13 @@ public void shouldLoginWithUserAndPassword() throws Exception { mockAPI .willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client .login("support@auth0.com", "voidpassword") .start(callback); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test @@ -210,11 +209,11 @@ public void shouldLoginWithUserAndPasswordSync() throws Exception { mockAPI .willReturnSuccessfulLogin(); - final Token token= client + final Credentials credentials = client .login("support@auth0.com", "voidpassword") .execute(); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test @@ -250,7 +249,7 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { mockAPI .willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithOAuthAccessToken("fbtoken", "facebook") .start(callback); @@ -262,14 +261,14 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { assertThat(body, hasEntry("access_token", "fbtoken")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test public void shouldLoginWithOAuthAccessTokenSync() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final Token token = client + final Credentials credentials = client .loginWithOAuthAccessToken("fbtoken", "facebook") .execute(); @@ -281,14 +280,14 @@ public void shouldLoginWithOAuthAccessTokenSync() throws Exception { assertThat(body, hasEntry("access_token", "fbtoken")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test public void shouldLoginWithPhoneNumber() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithPhoneNumber("+10101010101", "1234") .start(callback); @@ -301,14 +300,14 @@ public void shouldLoginWithPhoneNumber() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test public void shouldLoginWithPhoneNumberSync() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final Token token = client + final Credentials credentials = client .loginWithPhoneNumber("+10101010101", "1234") .execute(); @@ -321,14 +320,14 @@ public void shouldLoginWithPhoneNumberSync() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test public void shouldLoginWithEmailOnly() throws Exception { mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.loginWithEmail("support@auth0.com", "1234") .start(callback); @@ -341,7 +340,7 @@ public void shouldLoginWithEmailOnly() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test @@ -350,7 +349,7 @@ public void shouldLoginWithEmailOnlySync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Token token = client + final Credentials credentials = client .loginWithEmail("support@auth0.com", "1234") .execute(); @@ -363,7 +362,7 @@ public void shouldLoginWithEmailOnlySync() throws Exception { assertThat(body, hasEntry("password", "1234")); assertThat(body, hasEntry("scope", "openid offline_access")); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test @@ -448,7 +447,7 @@ public void shouldSignUpUser() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123", "support") .start(callback); @@ -460,7 +459,7 @@ public void shouldSignUpUser() throws Exception { assertThat(body, hasEntry("username", "support")); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test @@ -469,7 +468,7 @@ public void shouldSignUpUserSync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Token token = client + final Credentials credentials = client .signUp("support@auth0.com", "123123123", "support") .execute(); @@ -481,7 +480,7 @@ public void shouldSignUpUserSync() throws Exception { assertThat(body, hasEntry("username", "support")); assertThat(body, hasEntry("password", "123123123")); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test @@ -490,7 +489,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final MockBaseCallback callback = new MockBaseCallback<>(); + final MockBaseCallback callback = new MockBaseCallback<>(); client.signUp("support@auth0.com", "123123123") .start(callback); @@ -502,7 +501,7 @@ public void shouldSignUpUserWithoutUsername() throws Exception { assertThat(body, not(hasEntry("username", "support"))); assertThat(body, hasEntry("password", "123123123")); - assertThat(callback, hasPayloadOfType(Token.class)); + assertThat(callback, hasPayloadOfType(Credentials.class)); } @Test @@ -511,7 +510,7 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception { .willReturnSuccessfulLogin() .willReturnTokenInfo(); - final Token token = client + final Credentials credentials = client .signUp("support@auth0.com", "123123123") .execute(); @@ -523,7 +522,7 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception { assertThat(body, hasEntry("username", null)); assertThat(body, hasEntry("password", "123123123")); - assertThat(token, is(notNullValue())); + assertThat(credentials, is(notNullValue())); } @Test @@ -531,7 +530,7 @@ public void shouldChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.changePassword("support@auth0.com") + client.requestChangePassword("support@auth0.com") .setNewPassword("123123123") .start(callback); @@ -550,7 +549,7 @@ public void shouldChangePassword() throws Exception { public void shouldChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); - client.changePassword("support@auth0.com") + client.requestChangePassword("support@auth0.com") .setNewPassword("123123123") .execute(); @@ -568,7 +567,7 @@ public void shouldRequestChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.changePassword("support@auth0.com") + client.requestChangePassword("support@auth0.com") .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -586,7 +585,7 @@ public void shouldRequestChangePassword() throws Exception { public void shouldRequestChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); - client.changePassword("support@auth0.com") + client.requestChangePassword("support@auth0.com") .execute(); final RecordedRequest request = mockAPI.takeRequest(); From 5ff1af7ece4163ee5a6a0f2d8aac480c44499e23 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 11:11:33 -0300 Subject: [PATCH 54/89] Improve ParameterizableRequest API --- .../AuthenticationAPIClient.java | 107 ++++++++++-------- .../authentication/AuthenticationRequest.java | 12 +- .../authentication/ChangePasswordRequest.java | 19 ++-- .../authentication/DelegationRequest.java | 15 +-- .../authentication/ParameterBuilder.java | 4 +- .../auth0/authentication/SignUpRequest.java | 16 +-- .../java/com/auth0/internal/BaseRequest.java | 11 +- .../auth0/request/ParameterizableRequest.java | 18 ++- .../AuthenticationAPIClientTest.java | 12 +- 9 files changed, 116 insertions(+), 98 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index af694819..b6dda8fc 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -170,9 +170,8 @@ public ParameterizableRequest loginWithOAuthAccessToken(String toke .setAccessToken(token) .asDictionary(); - ParameterizableRequest credentialsRequest = factory.POST(url, client, mapper, Credentials.class); - credentialsRequest.getParameterBuilder().addAll(parameters); - return credentialsRequest; + return factory.POST(url, client, mapper, Credentials.class) + .addParameters(parameters); } /** @@ -218,9 +217,8 @@ public ParameterizableRequest loginWithEmail(String email, String v * @return a request to start */ public Request tokenInfo(String idToken) { - ParameterizableRequest request = profileRequest(); - request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); - return request; + return profileRequest() + .addParameter(ParameterBuilder.ID_TOKEN_KEY, idToken); } /** @@ -237,14 +235,15 @@ public ParameterizableRequest createUser(String email, String pass .addPathSegment(SIGN_UP_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class); - request.getParameterBuilder() + Map parameters = ParameterBuilder.newBuilder() .set(USERNAME_KEY, username) .set(EMAIL_KEY, email) .set(PASSWORD_KEY, password) .setConnection(defaultDbConnection) - .setClientId(getClientId()); - return request; + .setClientId(getClientId()) + .asDictionary(); + return factory.POST(url, client, mapper, DatabaseUser.class) + .addParameters(parameters); } /** @@ -299,11 +298,13 @@ public ChangePasswordRequest requestChangePassword(String email) { .addPathSegment(CHANGE_PASSWORD_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .set(EMAIL_KEY, email) .setClientId(getClientId()) - .setConnection(defaultDbConnection); + .setConnection(defaultDbConnection) + .asDictionary(); + ParameterizableRequest request = factory.POST(url, client, mapper) + .addParameters(parameters); return new ChangePasswordRequest(request); } @@ -314,8 +315,8 @@ public ChangePasswordRequest requestChangePassword(String email) { * @return a request to configure and start */ public DelegationRequest delegationWithIdToken(String idToken) { - ParameterizableRequest request = delegation(Delegation.class); - request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); + ParameterizableRequest request = delegation(Delegation.class) + .addParameter(ParameterBuilder.ID_TOKEN_KEY, idToken); return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); @@ -329,8 +330,8 @@ public DelegationRequest delegationWithIdToken(String idToken) { * @return a request to configure and start */ public DelegationRequest delegationWithRefreshToken(String refreshToken) { - ParameterizableRequest request = delegation(Delegation.class); - request.getParameterBuilder().set(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); + ParameterizableRequest request = delegation(Delegation.class) + .addParameter(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); return new DelegationRequest<>(request) .setApiType(DelegationRequest.DEFAULT_API_TYPE); @@ -344,8 +345,8 @@ public DelegationRequest delegationWithRefreshToken(String refreshTo * @return a request to configure and start */ public DelegationRequest> delegationWithIdToken(String idToken, String apiType) { - ParameterizableRequest> request = delegation(); - request.getParameterBuilder().set(ParameterBuilder.ID_TOKEN_KEY, idToken); + ParameterizableRequest> request = delegation() + .addParameter(ParameterBuilder.ID_TOKEN_KEY, idToken); return new DelegationRequest<>(request) .setApiType(apiType); @@ -360,8 +361,8 @@ public DelegationRequest> delegationWithIdToken(String idTok * @return a request to configure and start */ public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { - ParameterizableRequest> request = delegation(); - request.getParameterBuilder().set(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); + ParameterizableRequest> request = delegation() + .addParameter(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); return new DelegationRequest<>(request).setApiType(apiType); } @@ -378,12 +379,14 @@ public Request unlink(String userId, String accessToken) { .addPathSegment(UNLINK_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .setAccessToken(accessToken) .set(CLIENT_ID_KEY, getClientId()) - .set(USER_ID_KEY, userId); - return request; + .set(USER_ID_KEY, userId) + .asDictionary(); + + return factory.POST(url, client, mapper) + .addParameters(parameters); } /** @@ -394,12 +397,14 @@ public Request unlink(String userId, String accessToken) { * @return a request to configure and start */ public ParameterizableRequest passwordlessWithEmail(String email, PasswordlessType passwordlessType) { - ParameterizableRequest request = passwordless(); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .set(EMAIL_KEY, email) .setSend(passwordlessType) - .setConnection(EMAIL_CONNECTION); - return request; + .setConnection(EMAIL_CONNECTION) + .asDictionary(); + + return passwordless() + .addParameters(parameters); } /** @@ -410,12 +415,13 @@ public ParameterizableRequest passwordlessWithEmail(String email, Password * @return a request to configure and start */ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, PasswordlessType passwordlessType) { - ParameterizableRequest request = passwordless(); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .set(PHONE_NUMBER_KEY, phoneNumber) .setSend(passwordlessType) - .setConnection(SMS_CONNECTION); - return request; + .setConnection(SMS_CONNECTION) + .asDictionary(); + return passwordless() + .addParameters(parameters); } /** @@ -429,11 +435,12 @@ public ParameterizableRequest> delegation() { .addPathSegment(DELEGATION_PATH) .build(); - ParameterizableRequest> request = factory.rawPOST(url, client, mapper); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .setClientId(getClientId()) - .setGrantType(ParameterBuilder.GRANT_TYPE_JWT); - return request; + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) + .asDictionary(); + return factory.rawPOST(url, client, mapper) + .addParameters(parameters); } protected ParameterizableRequest delegation(Class clazz) { @@ -441,12 +448,13 @@ protected ParameterizableRequest delegation(Class clazz) { .addPathSegment(DELEGATION_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper, clazz); - request.getParameterBuilder() + final Map parameters = ParameterBuilder.newBuilder() .setClientId(getClientId()) - .setGrantType(GRANT_TYPE_JWT); + .setGrantType(ParameterBuilder.GRANT_TYPE_JWT) + .asDictionary(); - return request; + return factory.POST(url, client, mapper, clazz) + .addParameters(parameters); } /** @@ -460,9 +468,11 @@ public ParameterizableRequest passwordless() { .addPathSegment(START_PATH) .build(); - ParameterizableRequest request = factory.POST(url, client, mapper); - request.getParameterBuilder().setClientId(getClientId()); - return request; + final Map parameters = ParameterBuilder.newBuilder() + .setClientId(getClientId()) + .asDictionary(); + return factory.POST(url, client, mapper) + .addParameters(parameters); } /** @@ -482,12 +492,13 @@ protected ParameterizableRequest loginWithResourceOwner(Map request = factory.POST(url, client, mapper, Credentials.class); - request.getParameterBuilder() + final Map requestParameters = ParameterBuilder.newBuilder() .setClientId(getClientId()) .setConnection(defaultDbConnection) - .addAll(parameters); - return request; + .addAll(parameters) + .asDictionary(); + return factory.POST(url, client, mapper, Credentials.class) + .addParameters(requestParameters); } private ParameterizableRequest profileRequest() { diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java index 2f67cb3c..333b6090 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java @@ -56,7 +56,7 @@ public class AuthenticationRequest implements Request { * @return itself */ public AuthenticationRequest addParameters(Map parameters) { - credentialsRequest.getParameterBuilder().addAll(parameters); + credentialsRequest.addParameters(parameters); return this; } @@ -67,7 +67,7 @@ public AuthenticationRequest addParameters(Map parameters) { * @return itself */ public AuthenticationRequest setScope(String scope) { - credentialsRequest.getParameterBuilder().setScope(scope); + credentialsRequest.addParameter(ParameterBuilder.SCOPE_KEY, scope); return this; } @@ -78,7 +78,7 @@ public AuthenticationRequest setScope(String scope) { * @return itself */ public AuthenticationRequest setConnection(String connection) { - credentialsRequest.getParameterBuilder().setConnection(connection); + credentialsRequest.addParameter(ParameterBuilder.CONNECTION_KEY, connection); return this; } @@ -93,9 +93,7 @@ public void start(final BaseCallback callback) { @Override public void onSuccess(final Credentials credentials) { tokenInfoRequest - .getParameterBuilder() - .set(ID_TOKEN_KEY, credentials.getIdToken()); - tokenInfoRequest + .addParameter(ID_TOKEN_KEY, credentials.getIdToken()) .start(new BaseCallback() { @Override public void onSuccess(UserProfile profile) { @@ -125,8 +123,8 @@ public void onFailure(Auth0Exception error) { @Override public Authentication execute() throws Auth0Exception { Credentials credentials = credentialsRequest.execute(); - tokenInfoRequest.getParameterBuilder().set(ID_TOKEN_KEY, credentials.getIdToken()); UserProfile profile = tokenInfoRequest + .addParameter(ID_TOKEN_KEY, credentials.getIdToken()) .execute(); return new Authentication(profile, credentials); } diff --git a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java index e4bdde3b..5de68a71 100644 --- a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java @@ -42,7 +42,6 @@ public class ChangePasswordRequest implements ParameterizableRequest { ChangePasswordRequest(ParameterizableRequest request) { this.request = request; - request.getParameterBuilder(); } /** @@ -52,18 +51,20 @@ public class ChangePasswordRequest implements ParameterizableRequest { * @return itself */ public ChangePasswordRequest setNewPassword(String newPassword) { - request.getParameterBuilder().set(PASSWORD_KEY, newPassword); + request.addParameter(PASSWORD_KEY, newPassword); + return this; + } + + @Override + public ChangePasswordRequest addParameters(Map parameters) { + request.addParameters(parameters); return this; } - /** - * Getter for this request ParameterBuilder. - * - * @return the associated ParameterBuilder instance - */ @Override - public ParameterBuilder getParameterBuilder() { - return request.getParameterBuilder(); + public ChangePasswordRequest addParameter(String name, Object value) { + request.addParameter(name, value); + return this; } /** diff --git a/lib/src/main/java/com/auth0/authentication/DelegationRequest.java b/lib/src/main/java/com/auth0/authentication/DelegationRequest.java index eb8ad45e..0154ab6a 100644 --- a/lib/src/main/java/com/auth0/authentication/DelegationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/DelegationRequest.java @@ -53,11 +53,6 @@ public class DelegationRequest implements Request { this.request = request; } - private DelegationRequest addParameter(String key, Object value) { - request.getParameterBuilder().set(key, value); - return this; - } - /** * Add additional parameters to be sent in the request * @@ -65,7 +60,7 @@ private DelegationRequest addParameter(String key, Object value) { * @return itself */ public DelegationRequest addParameters(Map parameters) { - request.getParameterBuilder().addAll(parameters); + request.addParameters(parameters); return this; } @@ -76,7 +71,8 @@ public DelegationRequest addParameters(Map parameters) { * @return itself */ public DelegationRequest setApiType(String apiType) { - return addParameter(API_TYPE_KEY, apiType); + request.addParameter(API_TYPE_KEY, apiType); + return this; } /** @@ -86,7 +82,7 @@ public DelegationRequest setApiType(String apiType) { * @return itself */ public DelegationRequest setScope(String scope) { - request.getParameterBuilder().setScope(scope); + request.addParameter(ParameterBuilder.SCOPE_KEY, scope); return this; } @@ -97,7 +93,8 @@ public DelegationRequest setScope(String scope) { * @return itself */ public DelegationRequest setTarget(String target) { - return addParameter(TARGET_KEY, target); + request.addParameter(TARGET_KEY, target); + return this; } /** diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index f6e8393e..9b7ad88d 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -40,14 +40,14 @@ public class ParameterBuilder { public static final String SCOPE_OPENID = "openid"; public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; public static final String ID_TOKEN_KEY = "id_token"; + public static final String SCOPE_KEY = "scope"; public static final String REFRESH_TOKEN_KEY = "refresh_token"; + public static final String CONNECTION_KEY = "connection"; private static final String ACCESS_TOKEN_KEY = "access_token"; - private static final String CONNECTION_KEY = "connection"; private static final String SEND_KEY = "send"; private static final String CLIENT_ID_KEY = "client_id"; private static final String GRANT_TYPE_KEY = "grant_type"; - private static final String SCOPE_KEY = "scope"; private static final String DEVICE_KEY = "device"; private Map parameters; diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index e348bfa2..1546d8bd 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -31,6 +31,8 @@ import com.auth0.callback.BaseCallback; import com.auth0.authentication.result.DatabaseUser; +import org.omg.Dynamic.Parameter; + import java.util.Map; /** @@ -52,7 +54,7 @@ public class SignUpRequest implements Request { * @return itself */ public SignUpRequest addSignUpParameters(Map parameters) { - signUpRequest.getParameterBuilder().addAll(parameters); + signUpRequest.addParameters(parameters); return this; } @@ -62,9 +64,7 @@ public SignUpRequest addSignUpParameters(Map parameters) { * @return itself */ public SignUpRequest addAuthenticationParameters(Map parameters) { - authenticationRequest - .getParameterBuilder() - .addAll(parameters); + authenticationRequest.addParameters(parameters); return this; } @@ -74,9 +74,7 @@ public SignUpRequest addAuthenticationParameters(Map parameters) * @return itself */ public SignUpRequest setScope(String scope) { - authenticationRequest - .getParameterBuilder() - .setScope(scope); + authenticationRequest.addParameter(ParameterBuilder.SCOPE_KEY, scope); return this; } @@ -86,9 +84,7 @@ public SignUpRequest setScope(String scope) { * @return itself */ public SignUpRequest setConnection(String connection) { - authenticationRequest - .getParameterBuilder() - .setConnection(connection); + authenticationRequest.addParameter(ParameterBuilder.CONNECTION_KEY, connection); return this; } diff --git a/lib/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/internal/BaseRequest.java index 41f19d69..e8b9eb69 100644 --- a/lib/src/main/java/com/auth0/internal/BaseRequest.java +++ b/lib/src/main/java/com/auth0/internal/BaseRequest.java @@ -129,8 +129,15 @@ public AuthorizableRequest setBearer(String jwt) { } @Override - public ParameterBuilder getParameterBuilder() { - return builder; + public ParameterizableRequest addParameters(Map parameters) { + builder.addAll(parameters); + return this; + } + + @Override + public ParameterizableRequest addParameter(String name, Object value) { + builder.set(name, value); + return this; } @Override diff --git a/lib/src/main/java/com/auth0/request/ParameterizableRequest.java b/lib/src/main/java/com/auth0/request/ParameterizableRequest.java index 98c04526..8aa3dab4 100644 --- a/lib/src/main/java/com/auth0/request/ParameterizableRequest.java +++ b/lib/src/main/java/com/auth0/request/ParameterizableRequest.java @@ -24,7 +24,7 @@ package com.auth0.request; -import com.auth0.authentication.ParameterBuilder; +import java.util.Map; /** * Defines a request that can be configured (payload and headers) @@ -34,11 +34,19 @@ public interface ParameterizableRequest extends Request { /** - * Getter for this request ParameterBuilder. - * - * @return the associated ParameterBuilder instance + * Add parameters to the request as a Map of Object with the keys as String + * @param parameters to send with the request + * @return itself + */ + ParameterizableRequest addParameters(Map parameters); + + /** + * Add parameter to the request with a given name + * @param name of the parameter + * @param value of the parameter + * @return itself */ - ParameterBuilder getParameterBuilder(); + ParameterizableRequest addParameter(String name, Object value); /** * Adds an additional header for the request diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 7011d59f..6d420d5f 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -851,9 +851,9 @@ public void shouldStartPasswordless() throws Exception { .set("email", "support@auth0.com") .asDictionary(); - ParameterizableRequest pwRequest = client.passwordless(); - pwRequest.getParameterBuilder().addAll(parameters); - pwRequest.start(callback); + client.passwordless() + .addParameters(parameters) + .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/passwordless/start")); @@ -877,9 +877,9 @@ public void shouldStartPasswordlessSync() throws Exception { .set("email", "support@auth0.com") .asDictionary(); - ParameterizableRequest pwRequest = client.passwordless(); - pwRequest.getParameterBuilder().addAll(parameters); - pwRequest.execute(); + client.passwordless() + .addParameters(parameters) + .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/passwordless/start")); From 60238c1df0d4ed82c72a8310de5e09cbec681cc5 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 12:12:12 -0300 Subject: [PATCH 55/89] Intorduce authentication request --- .../AuthenticationAPIClient.java | 32 +++--- .../authentication/ParameterBuilder.java | 11 +- ...cationRequest.java => ProfileRequest.java} | 27 ++--- .../auth0/authentication/SignUpRequest.java | 17 ++- .../internal/BaseAuthenticationRequest.java | 105 ++++++++++++++++++ .../com/auth0/internal/RequestFactory.java | 21 +++- .../auth0/request/AuthenticationRequest.java | 67 +++++++++++ 7 files changed, 235 insertions(+), 45 deletions(-) rename lib/src/main/java/com/auth0/authentication/{AuthenticationRequest.java => ProfileRequest.java} (83%) create mode 100644 lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java create mode 100644 lib/src/main/java/com/auth0/request/AuthenticationRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index b6dda8fc..cf1f0f57 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -30,6 +30,7 @@ import com.auth0.authentication.result.Delegation; import com.auth0.authentication.result.UserProfile; import com.auth0.internal.RequestFactory; +import com.auth0.request.AuthenticationRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; import com.auth0.util.Metrics; @@ -39,7 +40,6 @@ import java.util.Map; -import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_JWT; import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_PASSWORD; /** @@ -142,7 +142,7 @@ public void setDefaultDbConnection(String defaultDbConnection) { * @param password of the user * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest login(String usernameOrEmail, String password) { + public AuthenticationRequest login(String usernameOrEmail, String password) { Map requestParameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, usernameOrEmail) .set(PASSWORD_KEY, password) @@ -158,7 +158,7 @@ public ParameterizableRequest login(String usernameOrEmail, String * @param connection that will be used to authenticate the user, e.g. 'facebook' * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithOAuthAccessToken(String token, String connection) { + public AuthenticationRequest loginWithOAuthAccessToken(String token, String connection) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(ACCESS_TOKEN_PATH) @@ -170,8 +170,8 @@ public ParameterizableRequest loginWithOAuthAccessToken(String toke .setAccessToken(token) .asDictionary(); - return factory.POST(url, client, mapper, Credentials.class) - .addParameters(parameters); + return factory.authenticationPOST(url, client, mapper) + .addAuthenticationParameters(parameters); } /** @@ -181,7 +181,7 @@ public ParameterizableRequest loginWithOAuthAccessToken(String toke * @param verificationCode sent by Auth0 via SMS * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { + public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) @@ -199,7 +199,7 @@ public ParameterizableRequest loginWithPhoneNumber(String phoneNumb * @param verificationCode sent by Auth0 via Email * @return a request to configure and start that will yield {@link Credentials} */ - public ParameterizableRequest loginWithEmail(String email, String verificationCode) { + public AuthenticationRequest loginWithEmail(String email, String verificationCode) { Map parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, email) .set(PASSWORD_KEY, verificationCode) @@ -268,7 +268,7 @@ public ParameterizableRequest createUser(String email, String pass */ public SignUpRequest signUp(String email, String password, String username) { final ParameterizableRequest createUserRequest = createUser(email, password, username); - final ParameterizableRequest authenticationRequest = login(email, password); + final AuthenticationRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -282,7 +282,7 @@ public SignUpRequest signUp(String email, String password, String username) { */ public SignUpRequest signUp(String email, String password) { ParameterizableRequest createUserRequest = createUser(email, password); - final ParameterizableRequest authenticationRequest = login(email, password); + final AuthenticationRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -478,15 +478,15 @@ public ParameterizableRequest passwordless() { /** * Fetch the user's profile after it's authenticated by a login request. * If the login request fails, the returned request will fail - * @param loginRequest that will authenticate a user with Auth0 and return a {@see Credentials} - * @return a {@see AuthenticationRequest} that first logins and the fetches the profile + * @param authenticationRequest that will authenticate a user with Auth0 and return a {@see Credentials} + * @return a {@see ProfileRequest} that first logins and the fetches the profile */ - public AuthenticationRequest getProfileAfter(ParameterizableRequest loginRequest) { + public ProfileRequest getProfileAfter(AuthenticationRequest authenticationRequest) { final ParameterizableRequest profileRequest = profileRequest(); - return new AuthenticationRequest(loginRequest, profileRequest); + return new ProfileRequest(authenticationRequest, profileRequest); } - protected ParameterizableRequest loginWithResourceOwner(Map parameters) { + protected AuthenticationRequest loginWithResourceOwner(Map parameters) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(RESOURCE_OWNER_PATH) @@ -497,8 +497,8 @@ protected ParameterizableRequest loginWithResourceOwner(Map profileRequest() { diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 9b7ad88d..f14d1ec0 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -43,12 +43,11 @@ public class ParameterBuilder { public static final String SCOPE_KEY = "scope"; public static final String REFRESH_TOKEN_KEY = "refresh_token"; public static final String CONNECTION_KEY = "connection"; - - private static final String ACCESS_TOKEN_KEY = "access_token"; - private static final String SEND_KEY = "send"; - private static final String CLIENT_ID_KEY = "client_id"; - private static final String GRANT_TYPE_KEY = "grant_type"; - private static final String DEVICE_KEY = "device"; + public static final String ACCESS_TOKEN_KEY = "access_token"; + public static final String SEND_KEY = "send"; + public static final String CLIENT_ID_KEY = "client_id"; + public static final String GRANT_TYPE_KEY = "grant_type"; + public static final String DEVICE_KEY = "device"; private Map parameters; diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java b/lib/src/main/java/com/auth0/authentication/ProfileRequest.java similarity index 83% rename from lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java rename to lib/src/main/java/com/auth0/authentication/ProfileRequest.java index 333b6090..e3a6c3c6 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/authentication/ProfileRequest.java @@ -25,26 +25,27 @@ package com.auth0.authentication; import com.auth0.Auth0Exception; +import com.auth0.authentication.result.Authentication; import com.auth0.authentication.result.Credentials; +import com.auth0.authentication.result.UserProfile; +import com.auth0.callback.BaseCallback; +import com.auth0.request.AuthenticationRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; -import com.auth0.callback.BaseCallback; -import com.auth0.authentication.result.UserProfile; -import com.auth0.authentication.result.Authentication; import java.util.Map; /** - * Represent a Authentication request that consist of a log in and a fetch profile requests + * Request to fetch a profile after a successful authentication with Auth0 Authentication API */ -public class AuthenticationRequest implements Request { +public class ProfileRequest implements Request { private static final String ID_TOKEN_KEY = "id_token"; - private final ParameterizableRequest credentialsRequest; + private final AuthenticationRequest credentialsRequest; private final ParameterizableRequest tokenInfoRequest; - AuthenticationRequest(ParameterizableRequest credentialsRequest, ParameterizableRequest tokenInfoRequest) { + ProfileRequest(AuthenticationRequest credentialsRequest, ParameterizableRequest tokenInfoRequest) { this.credentialsRequest = credentialsRequest; this.tokenInfoRequest = tokenInfoRequest; } @@ -55,8 +56,8 @@ public class AuthenticationRequest implements Request { * @param parameters as a non-null dictionary * @return itself */ - public AuthenticationRequest addParameters(Map parameters) { - credentialsRequest.addParameters(parameters); + public ProfileRequest addParameters(Map parameters) { + credentialsRequest.addAuthenticationParameters(parameters); return this; } @@ -66,8 +67,8 @@ public AuthenticationRequest addParameters(Map parameters) { * @param scope value * @return itself */ - public AuthenticationRequest setScope(String scope) { - credentialsRequest.addParameter(ParameterBuilder.SCOPE_KEY, scope); + public ProfileRequest setScope(String scope) { + credentialsRequest.setScope(scope); return this; } @@ -77,8 +78,8 @@ public AuthenticationRequest setScope(String scope) { * @param connection name * @return itself */ - public AuthenticationRequest setConnection(String connection) { - credentialsRequest.addParameter(ParameterBuilder.CONNECTION_KEY, connection); + public ProfileRequest setConnection(String connection) { + credentialsRequest.setConnection(connection); return this; } diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index 1546d8bd..17c08f36 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -26,12 +26,11 @@ import com.auth0.Auth0Exception; import com.auth0.authentication.result.Credentials; +import com.auth0.authentication.result.DatabaseUser; +import com.auth0.callback.BaseCallback; +import com.auth0.request.AuthenticationRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; -import com.auth0.callback.BaseCallback; -import com.auth0.authentication.result.DatabaseUser; - -import org.omg.Dynamic.Parameter; import java.util.Map; @@ -41,9 +40,9 @@ public class SignUpRequest implements Request { private final ParameterizableRequest signUpRequest; - private final ParameterizableRequest authenticationRequest; + private final AuthenticationRequest authenticationRequest; - SignUpRequest(ParameterizableRequest signUpRequest, ParameterizableRequest authenticationRequest) { + SignUpRequest(ParameterizableRequest signUpRequest, AuthenticationRequest authenticationRequest) { this.signUpRequest = signUpRequest; this.authenticationRequest = authenticationRequest; } @@ -64,7 +63,7 @@ public SignUpRequest addSignUpParameters(Map parameters) { * @return itself */ public SignUpRequest addAuthenticationParameters(Map parameters) { - authenticationRequest.addParameters(parameters); + authenticationRequest.addAuthenticationParameters(parameters); return this; } @@ -74,7 +73,7 @@ public SignUpRequest addAuthenticationParameters(Map parameters) * @return itself */ public SignUpRequest setScope(String scope) { - authenticationRequest.addParameter(ParameterBuilder.SCOPE_KEY, scope); + authenticationRequest.setScope(scope); return this; } @@ -84,7 +83,7 @@ public SignUpRequest setScope(String scope) { * @return itself */ public SignUpRequest setConnection(String connection) { - authenticationRequest.addParameter(ParameterBuilder.CONNECTION_KEY, connection); + authenticationRequest.setConnection(connection); return this; } diff --git a/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java b/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java new file mode 100644 index 00000000..be710102 --- /dev/null +++ b/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java @@ -0,0 +1,105 @@ +package com.auth0.internal; + +import com.auth0.authentication.result.Credentials; +import com.auth0.request.AuthenticationRequest; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.HttpUrl; +import com.squareup.okhttp.OkHttpClient; + +import java.util.Map; + +import static com.auth0.authentication.ParameterBuilder.ACCESS_TOKEN_KEY; +import static com.auth0.authentication.ParameterBuilder.CLIENT_ID_KEY; +import static com.auth0.authentication.ParameterBuilder.CONNECTION_KEY; +import static com.auth0.authentication.ParameterBuilder.DEVICE_KEY; +import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_KEY; +import static com.auth0.authentication.ParameterBuilder.SCOPE_KEY; + +/** + * Created by hernan on 3/16/16. + */ +public class BaseAuthenticationRequest extends SimpleRequest implements AuthenticationRequest { + + public BaseAuthenticationRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { + super(url, client, mapper, httpMethod, clazz); + } + + public BaseAuthenticationRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { + super(url, client, mapper, httpMethod); + } + + /** + * Sets the 'client_id' parameter + * + * @param clientId clientID + * @return itself + */ + @Override + public AuthenticationRequest setClientId(String clientId) { + addParameter(CLIENT_ID_KEY, clientId); + return this; + } + + /** + * Sets the 'grant_type' parameter + * + * @param grantType grant type + * @return itself + */ + @Override + public AuthenticationRequest setGrantType(String grantType) { + addParameter(GRANT_TYPE_KEY, grantType); + return this; + } + + /** + * Sets the 'connection' parameter + * + * @param connection name of the connection + * @return itself + */ + @Override + public AuthenticationRequest setConnection(String connection) { + addParameter(CONNECTION_KEY, connection); + return this; + } + + /** + * Sets the 'scope' parameter. + * + * @param scope a scope value + * @return itself + */ + public AuthenticationRequest setScope(String scope) { + addParameter(SCOPE_KEY, scope); + return this; + } + + /** + * Sets the 'device' parameter + * + * @param device a device name + * @return itself + */ + public AuthenticationRequest setDevice(String device) { + addParameter(DEVICE_KEY, device); + return this; + } + + /** + * Sets the 'access_token' parameter + * + * @param accessToken a access token + * @return itself + */ + public AuthenticationRequest setAccessToken(String accessToken) { + addParameter(ACCESS_TOKEN_KEY, accessToken); + return this; + } + + @Override + public AuthenticationRequest addAuthenticationParameters(Map parameters) { + addParameters(parameters); + return this; + } +} diff --git a/lib/src/main/java/com/auth0/internal/RequestFactory.java b/lib/src/main/java/com/auth0/internal/RequestFactory.java index 3294d41b..a25c5e6b 100644 --- a/lib/src/main/java/com/auth0/internal/RequestFactory.java +++ b/lib/src/main/java/com/auth0/internal/RequestFactory.java @@ -24,6 +24,8 @@ package com.auth0.internal; +import com.auth0.authentication.result.Credentials; +import com.auth0.request.AuthenticationRequest; import com.auth0.request.AuthorizableRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.util.Metrics; @@ -47,7 +49,15 @@ public void setUserAgent(String userAgent) { } public ParameterizableRequest GET(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); + final SimpleRequest request = new SimpleRequest<>(url, client, mapper, "GET", clazz); + addMetrics(request); + return request; + } + + public AuthenticationRequest authenticationPOST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { + final BaseAuthenticationRequest request = new BaseAuthenticationRequest(url, client, mapper, "POST", Credentials.class); + addMetrics(request); + return request; } public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { @@ -91,4 +101,13 @@ private ParameterizableRequest addMetricHeader(ParameterizableRequest } return request; } + + private void addMetrics(AuthorizableRequest request) { + if (this.clientInfo != null) { + request.addHeader(Metrics.HEADER_NAME, this.clientInfo); + } + if (this.userAgent!= null) { + request.addHeader("User-Agent", this.userAgent); + } + } } diff --git a/lib/src/main/java/com/auth0/request/AuthenticationRequest.java b/lib/src/main/java/com/auth0/request/AuthenticationRequest.java new file mode 100644 index 00000000..87489b83 --- /dev/null +++ b/lib/src/main/java/com/auth0/request/AuthenticationRequest.java @@ -0,0 +1,67 @@ +package com.auth0.request; + +import com.auth0.authentication.result.Credentials; + +import java.util.Map; + +/** + * Request to authenticate a user with Auth0 Authentication API + */ +public interface AuthenticationRequest extends Request { + + /** + * Sets the 'client_id' parameter + * + * @param clientId clientID + * @return itself + */ + AuthenticationRequest setClientId(String clientId); + + /** + * Sets the 'grant_type' parameter + * + * @param grantType grant type + * @return itself + */ + AuthenticationRequest setGrantType(String grantType); + + /** + * Sets the 'connection' parameter + * + * @param connection name of the connection + * @return itself + */ + AuthenticationRequest setConnection(String connection); + + /** + * Sets the 'scope' parameter. + * + * @param scope a scope value + * @return itself + */ + AuthenticationRequest setScope(String scope); + + /** + * Sets the 'device' parameter + * + * @param device a device name + * @return itself + */ + AuthenticationRequest setDevice(String device); + + /** + * Sets the 'access_token' parameter + * + * @param accessToken a access token + * @return itself + */ + AuthenticationRequest setAccessToken(String accessToken); + + /** + * All all entries of the map as parameters of this request + * @param parameters to be added to the request + * @return itself + */ + AuthenticationRequest addAuthenticationParameters(Map parameters); + +} From 12ca19ee3cf836118cbc72c6b8b7ffd170b6d925 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 12:43:25 -0300 Subject: [PATCH 56/89] Remove unused methods --- .../internal/BaseAuthenticationRequest.java | 13 ------- .../com/auth0/internal/RequestFactory.java | 35 ++++++++++--------- .../auth0/request/AuthenticationRequest.java | 8 ----- 3 files changed, 18 insertions(+), 38 deletions(-) diff --git a/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java b/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java index be710102..c1182854 100644 --- a/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java @@ -9,7 +9,6 @@ import java.util.Map; import static com.auth0.authentication.ParameterBuilder.ACCESS_TOKEN_KEY; -import static com.auth0.authentication.ParameterBuilder.CLIENT_ID_KEY; import static com.auth0.authentication.ParameterBuilder.CONNECTION_KEY; import static com.auth0.authentication.ParameterBuilder.DEVICE_KEY; import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_KEY; @@ -28,18 +27,6 @@ public BaseAuthenticationRequest(HttpUrl url, OkHttpClient client, ObjectMapper super(url, client, mapper, httpMethod); } - /** - * Sets the 'client_id' parameter - * - * @param clientId clientID - * @return itself - */ - @Override - public AuthenticationRequest setClientId(String clientId) { - addParameter(CLIENT_ID_KEY, clientId); - return this; - } - /** * Sets the 'grant_type' parameter * diff --git a/lib/src/main/java/com/auth0/internal/RequestFactory.java b/lib/src/main/java/com/auth0/internal/RequestFactory.java index a25c5e6b..48359cac 100644 --- a/lib/src/main/java/com/auth0/internal/RequestFactory.java +++ b/lib/src/main/java/com/auth0/internal/RequestFactory.java @@ -61,48 +61,49 @@ public AuthenticationRequest authenticationPOST(HttpUrl url, OkHttpClient client } public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new SimpleRequest<>(url, client, mapper, "POST", clazz)); + final SimpleRequest request = new SimpleRequest<>(url, client, mapper, "POST", clazz); + addMetrics(request); + return request; } public ParameterizableRequest> rawPOST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { final SimpleRequest> request = new SimpleRequest<>(url, client, mapper, "POST"); - addMetricHeader(request); + addMetrics(request); return request; } public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper) { - return addMetricHeader(new VoidRequest(url, client, mapper, "POST")); + final VoidRequest request = new VoidRequest(url, client, mapper, "POST"); + addMetrics(request); + return request; } public ParameterizableRequest POST(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String jwt) { final AuthorizableRequest request = new VoidRequest(url, client, mapper, "POST") .setBearer(jwt); - return addMetricHeader(request); + addMetrics(request); + return request; } public ParameterizableRequest PUT(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new SimpleRequest<>(url, client, mapper, "PUT", clazz)); + final SimpleRequest request = new SimpleRequest<>(url, client, mapper, "PUT", clazz); + addMetrics(request); + return request; } public ParameterizableRequest PATCH(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new SimpleRequest<>(url, client, mapper, "GET", clazz)); + final SimpleRequest request = new SimpleRequest<>(url, client, mapper, "GET", clazz); + addMetrics(request); + return request; } public ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, ObjectMapper mapper, Class clazz) { - return addMetricHeader(new SimpleRequest<>(url, client, mapper, "DELETE", clazz)); - } - - private ParameterizableRequest addMetricHeader(ParameterizableRequest request) { - if (this.clientInfo != null) { - request.addHeader(Metrics.HEADER_NAME, this.clientInfo); - } - if (this.userAgent!= null) { - request.addHeader("User-Agent", this.userAgent); - } + final SimpleRequest request = new SimpleRequest<>(url, client, mapper, "DELETE", clazz); + addMetrics(request); return request; } - private void addMetrics(AuthorizableRequest request) { + private void addMetrics(ParameterizableRequest request) { if (this.clientInfo != null) { request.addHeader(Metrics.HEADER_NAME, this.clientInfo); } diff --git a/lib/src/main/java/com/auth0/request/AuthenticationRequest.java b/lib/src/main/java/com/auth0/request/AuthenticationRequest.java index 87489b83..8bab1f4a 100644 --- a/lib/src/main/java/com/auth0/request/AuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/request/AuthenticationRequest.java @@ -9,14 +9,6 @@ */ public interface AuthenticationRequest extends Request { - /** - * Sets the 'client_id' parameter - * - * @param clientId clientID - * @return itself - */ - AuthenticationRequest setClientId(String clientId); - /** * Sets the 'grant_type' parameter * From 39975746326ac7714c33d596380960866d63c91e Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 14:54:05 -0300 Subject: [PATCH 57/89] Add DatabaseConnectionRequest For non-authentication related requests --- .../AuthenticationAPIClient.java | 16 +-- .../authentication/ChangePasswordRequest.java | 103 ------------------ .../DatabaseConnectionRequest.java | 79 ++++++++++++++ .../auth0/authentication/SignUpRequest.java | 5 +- .../AuthenticationAPIClientTest.java | 4 - 5 files changed, 90 insertions(+), 117 deletions(-) delete mode 100644 lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java create mode 100644 lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index cf1f0f57..e11d6090 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -229,7 +229,7 @@ public Request tokenInfo(String idToken) { * @param username of the user and must be non null * @return a request to start */ - public ParameterizableRequest createUser(String email, String password, String username) { + public DatabaseConnectionRequest createUser(String email, String password, String username) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(DB_CONNECTIONS_PATH) .addPathSegment(SIGN_UP_PATH) @@ -242,8 +242,9 @@ public ParameterizableRequest createUser(String email, String pass .setConnection(defaultDbConnection) .setClientId(getClientId()) .asDictionary(); - return factory.POST(url, client, mapper, DatabaseUser.class) + final ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); + return new DatabaseConnectionRequest(request); } /** @@ -253,7 +254,7 @@ public ParameterizableRequest createUser(String email, String pass * @param password of the user and must be non null * @return a request to start */ - public ParameterizableRequest createUser(String email, String password) { + public DatabaseConnectionRequest createUser(String email, String password) { return createUser(email, password, null); } @@ -267,7 +268,7 @@ public ParameterizableRequest createUser(String email, String pass * @return a request to configure and start that will yield {@link Credentials} */ public SignUpRequest signUp(String email, String password, String username) { - final ParameterizableRequest createUserRequest = createUser(email, password, username); + final DatabaseConnectionRequest createUserRequest = createUser(email, password, username); final AuthenticationRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -281,7 +282,7 @@ public SignUpRequest signUp(String email, String password, String username) { * @return a request to configure and start that will yield {@link Credentials} */ public SignUpRequest signUp(String email, String password) { - ParameterizableRequest createUserRequest = createUser(email, password); + DatabaseConnectionRequest createUserRequest = createUser(email, password); final AuthenticationRequest authenticationRequest = login(email, password); return new SignUpRequest(createUserRequest, authenticationRequest); } @@ -292,7 +293,7 @@ public SignUpRequest signUp(String email, String password) { * @param email of the user that changes the password. It's also where the email will be sent with the link to perform the change password. * @return a request to configure and start */ - public ChangePasswordRequest requestChangePassword(String email) { + public ParameterizableRequest requestChangePassword(String email) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(DB_CONNECTIONS_PATH) .addPathSegment(CHANGE_PASSWORD_PATH) @@ -303,9 +304,8 @@ public ChangePasswordRequest requestChangePassword(String email) { .setClientId(getClientId()) .setConnection(defaultDbConnection) .asDictionary(); - ParameterizableRequest request = factory.POST(url, client, mapper) + return factory.POST(url, client, mapper) .addParameters(parameters); - return new ChangePasswordRequest(request); } /** diff --git a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java b/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java deleted file mode 100644 index 5de68a71..00000000 --- a/lib/src/main/java/com/auth0/authentication/ChangePasswordRequest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ChangePasswordRequest.java - * - * Copyright (c) 2016 Auth0 (http://auth0.com) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package com.auth0.authentication; - -import com.auth0.Auth0Exception; -import com.auth0.request.ParameterizableRequest; -import com.auth0.callback.BaseCallback; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represent a request to change a user's password. - */ -public class ChangePasswordRequest implements ParameterizableRequest { - - private static final String PASSWORD_KEY = "password"; - - private final ParameterizableRequest request; - - ChangePasswordRequest(ParameterizableRequest request) { - this.request = request; - } - - /** - * Set the 'password' parameter to be sent in the request - * - * @param newPassword the new password - * @return itself - */ - public ChangePasswordRequest setNewPassword(String newPassword) { - request.addParameter(PASSWORD_KEY, newPassword); - return this; - } - - @Override - public ChangePasswordRequest addParameters(Map parameters) { - request.addParameters(parameters); - return this; - } - - @Override - public ChangePasswordRequest addParameter(String name, Object value) { - request.addParameter(name, value); - return this; - } - - /** - * Adds an additional header for the request - * - * @param name of the header - * @param value of the header - * @return itself - */ - @Override - public ChangePasswordRequest addHeader(String name, String value) { - request.addHeader(name, value); - return this; - } - - /** - * Starts the change password request - * - * @param callback called either on success or failure - */ - @Override - public void start(final BaseCallback callback) { - request.start(callback); - } - - /** - * Executes the change password request - * - * @return nothing on success - * @throws Auth0Exception when the change password request fails - */ - @Override - public Void execute() throws Auth0Exception { - return request.execute(); - } -} diff --git a/lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java b/lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java new file mode 100644 index 00000000..79d8257d --- /dev/null +++ b/lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java @@ -0,0 +1,79 @@ +package com.auth0.authentication; + +import com.auth0.Auth0Exception; +import com.auth0.callback.BaseCallback; +import com.auth0.request.ParameterizableRequest; + +import java.util.Map; + +/** + * Request to perform a non-authentication related action + * like creating a user or requesting a change password + */ +public class DatabaseConnectionRequest { + + private final ParameterizableRequest request; + + public DatabaseConnectionRequest(ParameterizableRequest request) { + this.request = request; + } + + /** + * Add the given parameters to the request + * @param parameters to be sent with the request + * @return itself + */ + public DatabaseConnectionRequest addParameters(Map parameters) { + request.addParameters(parameters); + return this; + } + + /** + * Add a parameter by name to the request + * @param name of the parameter + * @param value of the parameter + * @return itself + */ + public DatabaseConnectionRequest addParameter(String name, Object value) { + request.addParameter(name, value); + return this; + } + + /** + * Add a header for the request, e.g. "Authorization" + * @param name of the header + * @param value of the header + * @return itself + */ + public DatabaseConnectionRequest addHeader(String name, String value) { + request.addHeader(name, value); + return this; + } + + /** + * Set the Auth0 Database Connection used for this request using its name. + * @param connection name + * @return itself + */ + public DatabaseConnectionRequest setConnection(String connection) { + request.addParameter(ParameterBuilder.CONNECTION_KEY, connection); + return this; + } + + /** + * Executes the request async and returns its results via callback + * @param callback called on success or failure of the request + */ + public void start(BaseCallback callback) { + request.start(callback); + } + + /** + * Executes the request synchronously + * @return the request result + * @throws Auth0Exception if the request failed + */ + public T execute() throws Auth0Exception { + return request.execute(); + } +} diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index 17c08f36..18f775c0 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -39,10 +39,10 @@ */ public class SignUpRequest implements Request { - private final ParameterizableRequest signUpRequest; + private final DatabaseConnectionRequest signUpRequest; private final AuthenticationRequest authenticationRequest; - SignUpRequest(ParameterizableRequest signUpRequest, AuthenticationRequest authenticationRequest) { + SignUpRequest(DatabaseConnectionRequest signUpRequest, AuthenticationRequest authenticationRequest) { this.signUpRequest = signUpRequest; this.authenticationRequest = authenticationRequest; } @@ -83,6 +83,7 @@ public SignUpRequest setScope(String scope) { * @return itself */ public SignUpRequest setConnection(String connection) { + signUpRequest.setConnection(connection); authenticationRequest.setConnection(connection); return this; } diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 6d420d5f..7d01276d 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -531,7 +531,6 @@ public void shouldChangePassword() throws Exception { final MockBaseCallback callback = new MockBaseCallback<>(); client.requestChangePassword("support@auth0.com") - .setNewPassword("123123123") .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -540,7 +539,6 @@ public void shouldChangePassword() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("email", "support@auth0.com")); assertThat(body, not(hasKey("username"))); - assertThat(body, hasEntry("password", "123123123")); assertThat(callback, hasNoError()); } @@ -550,7 +548,6 @@ public void shouldChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); client.requestChangePassword("support@auth0.com") - .setNewPassword("123123123") .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -559,7 +556,6 @@ public void shouldChangePasswordSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("email", "support@auth0.com")); assertThat(body, not(hasKey("username"))); - assertThat(body, hasEntry("password", "123123123")); } @Test From 2b99dc2f7f792ca5ffe3a791983e81db59cd37bb Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 16:52:27 -0300 Subject: [PATCH 58/89] Make openid the default scope --- .../AuthenticationAPIClient.java | 5 +- .../authentication/ParameterBuilder.java | 2 +- .../AuthenticationAPIClientTest.java | 272 ++++++++++++------ .../authentication/ParameterBuilderTest.java | 8 +- 4 files changed, 200 insertions(+), 87 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index e11d6090..80410f21 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -293,7 +293,7 @@ public SignUpRequest signUp(String email, String password) { * @param email of the user that changes the password. It's also where the email will be sent with the link to perform the change password. * @return a request to configure and start */ - public ParameterizableRequest requestChangePassword(String email) { + public DatabaseConnectionRequest requestChangePassword(String email) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(DB_CONNECTIONS_PATH) .addPathSegment(CHANGE_PASSWORD_PATH) @@ -304,8 +304,9 @@ public ParameterizableRequest requestChangePassword(String email) { .setClientId(getClientId()) .setConnection(defaultDbConnection) .asDictionary(); - return factory.POST(url, client, mapper) + final ParameterizableRequest request = factory.POST(url, client, mapper) .addParameters(parameters); + return new DatabaseConnectionRequest<>(request); } /** diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index f14d1ec0..8463bb25 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -192,7 +192,7 @@ public Map asDictionary() { */ public static ParameterBuilder newAuthenticationBuilder() { return newBuilder() - .setScope(SCOPE_OFFLINE_ACCESS); + .setScope(SCOPE_OPENID); } /** diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 7d01276d..86105f64 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -66,6 +66,15 @@ public class AuthenticationAPIClientTest { private static final String CLIENT_ID = "CLIENTID"; private static final String DOMAIN = "samples.auth0.com"; private static final String CONNECTION = "DB"; + private static final String USERNAME_PASSWORD_AUTHENTICATION = "Username-Password-Authentication"; + private static final String PASSWORD = "123123123"; + private static final String SUPPORT_AUTH0_COM = "support@auth0.com"; + private static final String SUPPORT = "support"; + private static final String MY_CONNECTION = "MyConnection"; + private static final String FIRST_NAME = "John"; + private static final String LAST_NAME = "Doe"; + private static final String COMPANY = "Auth0"; + private static final String OPENID = "openid"; private AuthenticationAPIClient client; @@ -100,7 +109,7 @@ public void shouldLoginWithResourceOwner() throws Exception { final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection("DB") .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") + .set("username", SUPPORT_AUTH0_COM) .set("password", "notapassword") .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); @@ -116,9 +125,9 @@ public void shouldLoginWithResourceOwner() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "DB")); assertThat(body, hasEntry("grant_type", "password")); - assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("password", "notapassword")); - assertThat(body, hasEntry("scope", "openid")); + assertThat(body, hasEntry("scope", OPENID)); } @Test @@ -128,7 +137,7 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection("DB") .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") + .set("username", SUPPORT_AUTH0_COM) .set("password", "notapassword") .setScope(ParameterBuilder.SCOPE_OPENID) .asDictionary(); @@ -145,9 +154,9 @@ public void shouldLoginWithResourceOwnerSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "DB")); assertThat(body, hasEntry("grant_type", "password")); - assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("password", "notapassword")); - assertThat(body, hasEntry("scope", "openid")); + assertThat(body, hasEntry("scope", OPENID)); } @Test @@ -158,7 +167,7 @@ public void shouldFailLoginWithResourceOwner() throws Exception { final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") + .set("username", SUPPORT_AUTH0_COM) .set("password", "notapassword") .asDictionary(); client @@ -176,7 +185,7 @@ public void shouldFailLoginWithResourceOwnerSync() throws Exception { final Map parameters = ParameterBuilder.newAuthenticationBuilder() .setConnection(CONNECTION) .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", "support@auth0.com") + .set("username", SUPPORT_AUTH0_COM) .set("password", "notapassword") .asDictionary(); @@ -198,7 +207,7 @@ public void shouldLoginWithUserAndPassword() throws Exception { final MockBaseCallback callback = new MockBaseCallback<>(); client - .login("support@auth0.com", "voidpassword") + .login(SUPPORT_AUTH0_COM, "voidpassword") .start(callback); assertThat(callback, hasPayloadOfType(Credentials.class)); @@ -210,7 +219,7 @@ public void shouldLoginWithUserAndPasswordSync() throws Exception { .willReturnSuccessfulLogin(); final Credentials credentials = client - .login("support@auth0.com", "voidpassword") + .login(SUPPORT_AUTH0_COM, "voidpassword") .execute(); assertThat(credentials, is(notNullValue())); @@ -259,7 +268,7 @@ public void shouldLoginWithOAuthAccessToken() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "facebook")); assertThat(body, hasEntry("access_token", "fbtoken")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(callback, hasPayloadOfType(Credentials.class)); } @@ -278,7 +287,7 @@ public void shouldLoginWithOAuthAccessTokenSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "facebook")); assertThat(body, hasEntry("access_token", "fbtoken")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(credentials, is(notNullValue())); } @@ -298,7 +307,7 @@ public void shouldLoginWithPhoneNumber() throws Exception { assertThat(body, hasEntry("connection", "sms")); assertThat(body, hasEntry("username", "+10101010101")); assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(callback, hasPayloadOfType(Credentials.class)); } @@ -318,7 +327,7 @@ public void shouldLoginWithPhoneNumberSync() throws Exception { assertThat(body, hasEntry("connection", "sms")); assertThat(body, hasEntry("username", "+10101010101")); assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(credentials, is(notNullValue())); } @@ -328,7 +337,7 @@ public void shouldLoginWithEmailOnly() throws Exception { mockAPI.willReturnSuccessfulLogin(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.loginWithEmail("support@auth0.com", "1234") + client.loginWithEmail(SUPPORT_AUTH0_COM, "1234") .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -336,9 +345,9 @@ public void shouldLoginWithEmailOnly() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "email")); - assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(callback, hasPayloadOfType(Credentials.class)); } @@ -350,7 +359,7 @@ public void shouldLoginWithEmailOnlySync() throws Exception { .willReturnTokenInfo(); final Credentials credentials = client - .loginWithEmail("support@auth0.com", "1234") + .loginWithEmail(SUPPORT_AUTH0_COM, "1234") .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -358,9 +367,9 @@ public void shouldLoginWithEmailOnlySync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("connection", "email")); - assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("password", "1234")); - assertThat(body, hasEntry("scope", "openid offline_access")); + assertThat(body, hasEntry("scope", OPENID)); assertThat(credentials, is(notNullValue())); } @@ -370,16 +379,16 @@ public void shouldCreateUser() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.createUser("support@auth0.com", "123123123", "support") + client.createUser(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("username", SUPPORT)); + assertThat(body, hasEntry("password", PASSWORD)); assertThat(callback, hasPayloadOfType(DatabaseUser.class)); } @@ -389,16 +398,16 @@ public void shouldCreateUserSync() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final DatabaseUser user = client - .createUser("support@auth0.com", "123123123", "support") + .createUser(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("username", SUPPORT)); + assertThat(body, hasEntry("password", PASSWORD)); assertThat(user, is(notNullValue())); } @@ -408,16 +417,16 @@ public void shouldCreateUserWithoutUsername() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.createUser("support@auth0.com", "123123123") + client.createUser(SUPPORT_AUTH0_COM, PASSWORD) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, not(hasEntry("username", SUPPORT))); + assertThat(body, hasEntry("password", PASSWORD)); assertThat(callback, hasPayloadOfType(DatabaseUser.class)); } @@ -427,39 +436,111 @@ public void shouldCreateUserWithoutUsernameSync() throws Exception { mockAPI.willReturnSuccessfulSignUp(); final DatabaseUser user = client - .createUser("support@auth0.com", "123123123") + .createUser(SUPPORT_AUTH0_COM, PASSWORD) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("username", null)); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("password", PASSWORD)); assertThat(user, is(notNullValue())); } @Test public void shouldSignUpUser() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.signUp(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT) + .start(callback); + + final RecordedRequest createRequest = mockAPI.takeRequest(); + assertThat(createRequest.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(createRequest); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("username", SUPPORT)); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); + + assertThat(callback, hasPayloadOfType(Credentials.class)); + + final RecordedRequest loginRequest = mockAPI.takeRequest(); + assertThat(loginRequest.getPath(), equalTo("/oauth/ro")); + + Map loginBody = bodyFromRequest(loginRequest); + assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM)); + assertThat(loginBody, hasEntry("password", PASSWORD)); + assertThat(loginBody, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); + assertThat(loginBody, hasEntry("scope", OPENID)); + } + + @Test + public void shouldSignUpUserWithCustomFields() throws Exception { + mockAPI.willReturnSuccessfulSignUp() + .willReturnSuccessfulLogin(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + final Map custom = ParameterBuilder.newBuilder() + .set("first_name", FIRST_NAME) + .set("last_name", LAST_NAME) + .set("company", COMPANY) + .asDictionary(); + + client.signUp(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT) + .addSignUpParameters(custom) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/signup")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("username", SUPPORT)); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); + assertThat(body, hasEntry("first_name", FIRST_NAME)); + assertThat(body, hasEntry("last_name", LAST_NAME)); + assertThat(body, hasEntry("company", COMPANY)); + + assertThat(callback, hasPayloadOfType(Credentials.class)); + } + + @Test + public void shouldSignUpUserWithConnectionName() throws Exception { mockAPI.willReturnSuccessfulSignUp() .willReturnSuccessfulLogin() .willReturnTokenInfo(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.signUp("support@auth0.com", "123123123", "support") + client.signUp(SUPPORT_AUTH0_COM, PASSWORD) + .setConnection(MY_CONNECTION) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", MY_CONNECTION)); assertThat(callback, hasPayloadOfType(Credentials.class)); + + final RecordedRequest loginRequest = mockAPI.takeRequest(); + assertThat(loginRequest.getPath(), equalTo("/oauth/ro")); + + Map loginBody = bodyFromRequest(loginRequest); + assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM)); + assertThat(loginBody, hasEntry("password", PASSWORD)); + assertThat(loginBody, hasEntry("connection", MY_CONNECTION)); + assertThat(loginBody, hasEntry("scope", OPENID)); + } @Test @@ -469,18 +550,28 @@ public void shouldSignUpUserSync() throws Exception { .willReturnTokenInfo(); final Credentials credentials = client - .signUp("support@auth0.com", "123123123", "support") + .signUp(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, hasEntry("username", "support")); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("username", SUPPORT)); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); assertThat(credentials, is(notNullValue())); + + final RecordedRequest loginRequest = mockAPI.takeRequest(); + assertThat(loginRequest.getPath(), equalTo("/oauth/ro")); + + Map loginBody = bodyFromRequest(loginRequest); + assertThat(loginBody, hasEntry("username", SUPPORT_AUTH0_COM)); + assertThat(loginBody, hasEntry("password", PASSWORD)); + assertThat(loginBody, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); + assertThat(loginBody, hasEntry("scope", OPENID)); } @Test @@ -490,16 +581,17 @@ public void shouldSignUpUserWithoutUsername() throws Exception { .willReturnTokenInfo(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.signUp("support@auth0.com", "123123123") + client.signUp(SUPPORT_AUTH0_COM, PASSWORD) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); - assertThat(body, not(hasEntry("username", "support"))); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, not(hasEntry("username", SUPPORT))); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); assertThat(callback, hasPayloadOfType(Credentials.class)); } @@ -511,16 +603,17 @@ public void shouldSignUpUserWithoutUsernameSync() throws Exception { .willReturnTokenInfo(); final Credentials credentials = client - .signUp("support@auth0.com", "123123123") + .signUp(SUPPORT_AUTH0_COM, PASSWORD) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/signup")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("username", null)); - assertThat(body, hasEntry("password", "123123123")); + assertThat(body, hasEntry("password", PASSWORD)); + assertThat(body, hasEntry("connection", USERNAME_PASSWORD_AUTHENTICATION)); assertThat(credentials, is(notNullValue())); } @@ -530,14 +623,14 @@ public void shouldChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.requestChangePassword("support@auth0.com") + client.requestChangePassword(SUPPORT_AUTH0_COM) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/change_password")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, not(hasKey("username"))); assertThat(callback, hasNoError()); @@ -547,14 +640,14 @@ public void shouldChangePassword() throws Exception { public void shouldChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); - client.requestChangePassword("support@auth0.com") + client.requestChangePassword(SUPPORT_AUTH0_COM) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/change_password")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, not(hasKey("username"))); } @@ -563,32 +656,51 @@ public void shouldRequestChangePassword() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.requestChangePassword("support@auth0.com") + client.requestChangePassword(SUPPORT_AUTH0_COM) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/change_password")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, not(hasKey("username"))); assertThat(body, not(hasKey("password"))); assertThat(callback, hasNoError()); } + @Test + public void shouldRequestChangePasswordForAConnection() throws Exception { + mockAPI.willReturnSuccessfulChangePassword(); + + final MockBaseCallback callback = new MockBaseCallback<>(); + client.requestChangePassword(SUPPORT_AUTH0_COM) + .setConnection(MY_CONNECTION) + .start(callback); + + final RecordedRequest request = mockAPI.takeRequest(); + assertThat(request.getPath(), equalTo("/dbconnections/change_password")); + + Map body = bodyFromRequest(request); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); + assertThat(body, hasEntry("connection", MY_CONNECTION)); + + assertThat(callback, hasNoError()); + } + @Test public void shouldRequestChangePasswordSync() throws Exception { mockAPI.willReturnSuccessfulChangePassword(); - client.requestChangePassword("support@auth0.com") + client.requestChangePassword(SUPPORT_AUTH0_COM) .execute(); final RecordedRequest request = mockAPI.takeRequest(); assertThat(request.getPath(), equalTo("/dbconnections/change_password")); Map body = bodyFromRequest(request); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, not(hasKey("username"))); assertThat(body, not(hasKey("password"))); } @@ -844,7 +956,7 @@ public void shouldStartPasswordless() throws Exception { final Map parameters = ParameterBuilder.newBuilder() .setConnection("email") .set("send", "code") - .set("email", "support@auth0.com") + .set("email", SUPPORT_AUTH0_COM) .asDictionary(); client.passwordless() @@ -856,7 +968,7 @@ public void shouldStartPasswordless() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "code")); assertThat(body, hasEntry("connection", "email")); @@ -870,7 +982,7 @@ public void shouldStartPasswordlessSync() throws Exception { final Map parameters = ParameterBuilder.newBuilder() .setConnection("email") .set("send", "code") - .set("email", "support@auth0.com") + .set("email", SUPPORT_AUTH0_COM) .asDictionary(); client.passwordless() @@ -882,7 +994,7 @@ public void shouldStartPasswordlessSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "code")); assertThat(body, hasEntry("connection", "email")); } @@ -892,7 +1004,7 @@ public void shouldSendEmailCode() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.CODE) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.CODE) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -900,7 +1012,7 @@ public void shouldSendEmailCode() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "code")); assertThat(body, hasEntry("connection", "email")); @@ -911,7 +1023,7 @@ public void shouldSendEmailCode() throws Exception { public void shouldSendEmailCodeSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.CODE) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.CODE) .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -919,7 +1031,7 @@ public void shouldSendEmailCodeSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "code")); assertThat(body, hasEntry("connection", "email")); } @@ -929,7 +1041,7 @@ public void shouldSendEmailLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -937,7 +1049,7 @@ public void shouldSendEmailLink() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link")); assertThat(body, hasEntry("connection", "email")); @@ -948,7 +1060,7 @@ public void shouldSendEmailLink() throws Exception { public void shouldSendEmailLinkSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK) .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -956,7 +1068,7 @@ public void shouldSendEmailLinkSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link")); assertThat(body, hasEntry("connection", "email")); } @@ -966,7 +1078,7 @@ public void shouldSendEmailLinkAndroid() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_ANDROID) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_ANDROID) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -974,7 +1086,7 @@ public void shouldSendEmailLinkAndroid() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link_android")); assertThat(body, hasEntry("connection", "email")); @@ -985,7 +1097,7 @@ public void shouldSendEmailLinkAndroid() throws Exception { public void shouldSendEmailLinkAndroidSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_ANDROID) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_ANDROID) .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -993,7 +1105,7 @@ public void shouldSendEmailLinkAndroidSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link_android")); assertThat(body, hasEntry("connection", "email")); } @@ -1003,7 +1115,7 @@ public void shouldSendEmailLinkIOS() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_IOS) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_IOS) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -1011,7 +1123,7 @@ public void shouldSendEmailLinkIOS() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link_ios")); assertThat(body, hasEntry("connection", "email")); @@ -1022,7 +1134,7 @@ public void shouldSendEmailLinkIOS() throws Exception { public void shouldSendEmailLinkIOSSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithEmail("support@auth0.com", PasswordlessType.LINK_IOS) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_IOS) .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -1030,7 +1142,7 @@ public void shouldSendEmailLinkIOSSync() throws Exception { Map body = bodyFromRequest(request); assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("email", "support@auth0.com")); + assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("send", "link_ios")); assertThat(body, hasEntry("connection", "email")); } @@ -1190,14 +1302,14 @@ public void shouldFetchProfileAfterLoginRequest() throws Exception { .willReturnTokenInfo(); MockBaseCallback callback = new MockBaseCallback<>(); - client.getProfileAfter(client.login("support@auth0.com", "voidpassword")) + client.getProfileAfter(client.login(SUPPORT_AUTH0_COM, "voidpassword")) .start(callback); final RecordedRequest firstRequest = mockAPI.takeRequest(); assertThat(firstRequest.getPath(), equalTo("/oauth/ro")); Map body = bodyFromRequest(firstRequest); - assertThat(body, hasEntry("username", "support@auth0.com")); + assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); assertThat(body, hasEntry("password", "voidpassword")); final RecordedRequest secondRequest = mockAPI.takeRequest(); diff --git a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java index f86b82bc..d4bbf692 100644 --- a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java +++ b/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java @@ -65,7 +65,7 @@ public void shouldInstantiateWithNoArguments() throws Exception { @Test public void shouldInstantiateWithDefaultScope() throws Exception { - assertThat(ParameterBuilder.newAuthenticationBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(ParameterBuilder.newAuthenticationBuilder().asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); } @Test @@ -87,8 +87,8 @@ public void shouldSetClientID() throws Exception { @Test public void shouldSetScope() throws Exception { - Map parameters = builder.setScope(ParameterBuilder.SCOPE_OPENID).asDictionary(); - assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); + Map parameters = builder.setScope(ParameterBuilder.SCOPE_OFFLINE_ACCESS).asDictionary(); + assertThat(parameters, hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); } @Test @@ -127,7 +127,7 @@ public void shouldAddAllFromDictionary() throws Exception { @Test public void shouldDoNothingWhenAddingNullParameters() throws Exception { - assertThat(builder.addAll(null).asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OFFLINE_ACCESS)); + assertThat(builder.addAll(null).asDictionary(), hasEntry("scope", ParameterBuilder.SCOPE_OPENID)); } @Test From 18aafc61605fea0d4408b1747e2b1531fda2df74 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Wed, 16 Mar 2016 15:07:03 -0300 Subject: [PATCH 59/89] add example snippets to the APIClient class --- .../AuthenticationAPIClient.java | 212 +++++++++++++++++- 1 file changed, 209 insertions(+), 3 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 80410f21..d749bc92 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -136,11 +136,23 @@ public void setDefaultDbConnection(String defaultDbConnection) { } /** - * Log in a user with email/username and password using a DB connection + * Log in a user with email/username and password using a DB connection. + * Example usage: + *

+     * client.login("username", "password")
+     *      .setConnection("second-database")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) { }
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param usernameOrEmail of the user depending of the type of DB connection * @param password of the user - * @return a request to configure and start that will yield {@link Credentials} + * @return a request to configure and start that will yield{@link Credentials} */ public AuthenticationRequest login(String usernameOrEmail, String password) { Map requestParameters = ParameterBuilder.newAuthenticationBuilder() @@ -153,6 +165,18 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { /** * Log in a user with a OAuth 'access_token' of a Identity Provider like Facebook or Twitter using '\oauth\access_token' endpoint + * Example usage: + *

+     * client.loginWithOAuthAccessToken("token", "my-connection")
+     *      .setConnection("second-database")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) { }
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param token obtained from the IdP * @param connection that will be used to authenticate the user, e.g. 'facebook' @@ -176,6 +200,17 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn /** * Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) + * Example usage: + *

+     * client.loginWithPhoneNumber("1234567890", "000000")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) { }
+     * 

+ * {@literal@}@Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param phoneNumber where the user received the verification code * @param verificationCode sent by Auth0 via SMS @@ -194,6 +229,17 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver /** * Log in a user using an email and a verification code received via Email (Part of passwordless login flow) + * Example usage: + *

+     * client.loginWithEmail("email@example.com", "000000")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) { }
+     * 

+ * {@literal@}@Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param email where the user received the verification code * @param verificationCode sent by Auth0 via Email @@ -212,6 +258,17 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod /** * Fetch the token information from Auth0 + * Example usage: + *

+     * client.tokenInfo("idToken")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(UserProfile payload) { }
+     * 

+ * {@literal@}@Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param idToken used to fetch it's information * @return a request to start @@ -223,6 +280,18 @@ public Request tokenInfo(String idToken) { /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * Example usage: + *

+     * client.createUser("email@example.com", "password", "username")
+     *      .setConnection("Username-Password-Authentication")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(DatabaseUser payload) { }
+     * 

+ * {@literal@}@Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param email of the user and must be non null * @param password of the user and must be non null @@ -244,11 +313,23 @@ public DatabaseConnectionRequest createUser(String email, String p .asDictionary(); final ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class) .addParameters(parameters); - return new DatabaseConnectionRequest(request); + return new DatabaseConnectionRequest<>(request); } /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint + * Example usage: + *

+     * client.createUser("email@example.com", "password")
+     *      .setConnection("Username-Password-Authentication")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(DatabaseUser payload) { }
+     * 

+ * {@literal@}@Override + * public void onFailure(Auth0Exception error) { } + * }); + *

* * @param email of the user and must be non null * @param password of the user and must be non null @@ -261,6 +342,18 @@ public DatabaseConnectionRequest createUser(String email, String p /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint * and then logs in + * Example usage: + *

+     * client.signUp("email@example.com", "password", "username")
+     *      .setConnection("Username-Password-Authentication")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param email of the user and must be non null * @param password of the user and must be non null @@ -276,6 +369,18 @@ public SignUpRequest signUp(String email, String password, String username) { /** * Creates a user in a DB connection using '/dbconnections/signup' endpoint * and then logs in + * Example usage: + *

+     * client.signUp("email@example.com", "password")
+     *      .setConnection("Username-Password-Authentication")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Credentials payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param email of the user and must be non null * @param password of the user and must be non null @@ -289,6 +394,17 @@ public SignUpRequest signUp(String email, String password) { /** * Request a change password using '/dbconnections/change_password' + * Example usage: + *

+     * client.requestChangePassword("email@example.com")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Void payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param email of the user that changes the password. It's also where the email will be sent with the link to perform the change password. * @return a request to configure and start @@ -311,6 +427,17 @@ public DatabaseConnectionRequest requestChangePassword(String email) { /** * Performs a delegation request that will yield a new Auth0 'id_token' + * Example usage: + *

+     * client.delegationWithIdToken("idToken")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Delegation payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param idToken issued by Auth0 for the user. The token must not be expired. * @return a request to configure and start @@ -326,6 +453,17 @@ public DelegationRequest delegationWithIdToken(String idToken) { /** * Performs a delegation request that will yield a new Auth0 'id_token'. * Check our refresh token docs for more information + * Example usage: + *

+     * client.delegationWithRefreshToken("refreshToken")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Delegation payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. * @return a request to configure and start @@ -340,6 +478,17 @@ public DelegationRequest delegationWithRefreshToken(String refreshTo /** * Performs a delegation request that will yield a delegation token. + * Example usage: + *

+     * client.delegationWithIdToken("idToken", "firebase")
+     *      .start(new BaseCallback>() {
+     *          {@literal@}Override
+     *          public void onSuccess(Map payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param idToken issued by Auth0 for the user. The token must not be expired. * @param apiType the delegation 'api_type' parameter @@ -356,6 +505,17 @@ public DelegationRequest> delegationWithIdToken(String idTok /** * Performs a delegation request that will yield a delegation token. * Check our refresh token docs for more information + * Example usage: + *

+     * client.delegationWithRefreshToken("idToken", "firebase")
+     *      .start(new BaseCallback>() {
+     *          {@literal@}Override
+     *          public void onSuccess(Map payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. * @param apiType the delegation 'api_type' parameter @@ -370,6 +530,17 @@ public DelegationRequest> delegationWithRefreshToken(String /** * Unlink a user identity calling '/unlink' endpoint + * Example usage: + *

+     * client.unlink("auth0|userId", "accessToken")
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Void payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param userId of the identity to unlink * @param accessToken of the main identity obtained after login @@ -392,6 +563,17 @@ public Request unlink(String userId, String accessToken) { /** * Start a passwordless flow with Email + * Example usage: + *

+     * client.passwordlessWithEmail("email@example.com", PasswordlessType.CODE)
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Void payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param email that will receive a verification code to use for login * @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS) @@ -410,6 +592,17 @@ public ParameterizableRequest passwordlessWithEmail(String email, Password /** * Start a passwordless flow with SMS + * Example usage: + *

+     * client.passwordlessWithSms("1234567890", PasswordlessType.CODE)
+     *      .start(new BaseCallback() {
+     *          {@literal@}Override
+     *          public void onSuccess(Void payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @param phoneNumber where an SMS with a verification code will be sent * @param passwordlessType indicate whether the SMS should contain a code, link or magic link (android & iOS) @@ -428,6 +621,18 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass /** * Performs a custom delegation request that will * yield a delegation token. + * Example usage: + *

+     * client.delegation()
+     *      .addParameter("api_type", "firebase")
+     *      .start(new BaseCallback>() {
+     *          {@literal@}Override
+     *          public void onSuccess(Map payload) {}
+     * 

+ * {@literal@}Override + * public void onFailure(Auth0Exception error) {} + * }); + *

* * @return a request to configure and start */ @@ -479,6 +684,7 @@ public ParameterizableRequest passwordless() { /** * Fetch the user's profile after it's authenticated by a login request. * If the login request fails, the returned request will fail + * * @param authenticationRequest that will authenticate a user with Auth0 and return a {@see Credentials} * @return a {@see ProfileRequest} that first logins and the fetches the profile */ From 9f1bac6e9b51af3efde20b2a6ab3542b15169422 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Wed, 16 Mar 2016 17:36:23 -0300 Subject: [PATCH 60/89] Some docs update --- .../AuthenticationAPIClient.java | 102 +++++++----------- .../AuthenticationAPIClientTest.java | 46 +------- 2 files changed, 39 insertions(+), 109 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index d749bc92..1b26c5a8 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -139,12 +139,12 @@ public void setDefaultDbConnection(String defaultDbConnection) { * Log in a user with email/username and password using a DB connection. * Example usage: *

-     * client.login("username", "password")
+     * client.login("{username or email}", "{password}")
      *      .setConnection("second-database")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) { }
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) { } * }); @@ -152,7 +152,7 @@ public void setDefaultDbConnection(String defaultDbConnection) { * * @param usernameOrEmail of the user depending of the type of DB connection * @param password of the user - * @return a request to configure and start that will yield{@link Credentials} + * @return a request to configure and start that will yield {@link Credentials} */ public AuthenticationRequest login(String usernameOrEmail, String password) { Map requestParameters = ParameterBuilder.newAuthenticationBuilder() @@ -167,12 +167,12 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { * Log in a user with a OAuth 'access_token' of a Identity Provider like Facebook or Twitter using '\oauth\access_token' endpoint * Example usage: *


-     * client.loginWithOAuthAccessToken("token", "my-connection")
+     * client.loginWithOAuthAccessToken("{token}", "{connection name}")
      *      .setConnection("second-database")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) { }
-     * 

+ * {@literal@}Override * public void onFailure(Auth0Exception error) { } * }); @@ -202,11 +202,11 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn * Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) * Example usage: *


-     * client.loginWithPhoneNumber("1234567890", "000000")
+     * client.loginWithPhoneNumber("{phone number}", "{code}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) { }
-     * 

+ * {@literal@}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -231,11 +231,11 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver * Log in a user using an email and a verification code received via Email (Part of passwordless login flow) * Example usage: *


-     * client.loginWithEmail("email@example.com", "000000")
+     * client.loginWithEmail("{email}", "{code}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) { }
-     * 

+ * {@literal@}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -260,11 +260,11 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod * Fetch the token information from Auth0 * Example usage: *


-     * client.tokenInfo("idToken")
+     * client.tokenInfo("{id_token}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(UserProfile payload) { }
-     * 

+ * {@literal@}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -282,12 +282,12 @@ public Request tokenInfo(String idToken) { * Creates a user in a DB connection using '/dbconnections/signup' endpoint * Example usage: *


-     * client.createUser("email@example.com", "password", "username")
-     *      .setConnection("Username-Password-Authentication")
+     * client.createUser("{email}", "{password}", "{username}")
+     *      .setConnection("{connection name}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(DatabaseUser payload) { }
-     * 

+ * * {@literal@}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -320,12 +320,12 @@ public DatabaseConnectionRequest createUser(String email, String p * Creates a user in a DB connection using '/dbconnections/signup' endpoint * Example usage: *


-     * client.createUser("email@example.com", "password")
-     *      .setConnection("Username-Password-Authentication")
+     * client.createUser("{email}", "{password}")
+     *      .setConnection("{connection name}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(DatabaseUser payload) { }
-     * 

+ * * {@literal@}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -344,12 +344,12 @@ public DatabaseConnectionRequest createUser(String email, String p * and then logs in * Example usage: *


-     * client.signUp("email@example.com", "password", "username")
-     *      .setConnection("Username-Password-Authentication")
+     * client.signUp("{email}", "{password}", "{username}")
+     *      .setConnection("{connection name}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -371,12 +371,12 @@ public SignUpRequest signUp(String email, String password, String username) { * and then logs in * Example usage: *


-     * client.signUp("email@example.com", "password")
-     *      .setConnection("Username-Password-Authentication")
+     * client.signUp("{email}", "{password}")
+     *      .setConnection("{connection name}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -396,11 +396,11 @@ public SignUpRequest signUp(String email, String password) { * Request a change password using '/dbconnections/change_password' * Example usage: *


-     * client.requestChangePassword("email@example.com")
+     * client.requestChangePassword("{email}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Void payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -429,11 +429,11 @@ public DatabaseConnectionRequest requestChangePassword(String email) { * Performs a delegation request that will yield a new Auth0 'id_token' * Example usage: *


-     * client.delegationWithIdToken("idToken")
+     * client.delegationWithIdToken("{id token}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Delegation payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -455,11 +455,11 @@ public DelegationRequest delegationWithIdToken(String idToken) { * Check our refresh token docs for more information * Example usage: *


-     * client.delegationWithRefreshToken("refreshToken")
+     * client.delegationWithRefreshToken("{refresh token}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Delegation payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -480,11 +480,11 @@ public DelegationRequest delegationWithRefreshToken(String refreshTo * Performs a delegation request that will yield a delegation token. * Example usage: *


-     * client.delegationWithIdToken("idToken", "firebase")
+     * client.delegationWithIdToken("{id token}", "{app type, e.g. firebase}")
      *      .start(new BaseCallback>() {
      *          {@literal@}Override
      *          public void onSuccess(Map payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -502,41 +502,15 @@ public DelegationRequest> delegationWithIdToken(String idTok .setApiType(apiType); } - /** - * Performs a delegation request that will yield a delegation token. - * Check our refresh token docs for more information - * Example usage: - *


-     * client.delegationWithRefreshToken("idToken", "firebase")
-     *      .start(new BaseCallback>() {
-     *          {@literal@}Override
-     *          public void onSuccess(Map payload) {}
-     * 

- * {@literal@}Override - * public void onFailure(Auth0Exception error) {} - * }); - *

- * - * @param refreshToken issued by Auth0 for the user when using the 'offline_access' scope when logging in. - * @param apiType the delegation 'api_type' parameter - * @return a request to configure and start - */ - public DelegationRequest> delegationWithRefreshToken(String refreshToken, String apiType) { - ParameterizableRequest> request = delegation() - .addParameter(ParameterBuilder.REFRESH_TOKEN_KEY, refreshToken); - - return new DelegationRequest<>(request).setApiType(apiType); - } - /** * Unlink a user identity calling '/unlink' endpoint * Example usage: *

-     * client.unlink("auth0|userId", "accessToken")
+     * client.unlink("{auth0 user id}", "{user access token}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Void payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -565,11 +539,11 @@ public Request unlink(String userId, String accessToken) { * Start a passwordless flow with Email * Example usage: *


-     * client.passwordlessWithEmail("email@example.com", PasswordlessType.CODE)
+     * client.passwordlessWithEmail("{email}", PasswordlessType.CODE)
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Void payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -594,11 +568,11 @@ public ParameterizableRequest passwordlessWithEmail(String email, Password * Start a passwordless flow with SMS * Example usage: *


-     * client.passwordlessWithSms("1234567890", PasswordlessType.CODE)
+     * client.passwordlessWithSms("{phone number}", PasswordlessType.CODE)
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Void payload) {}
-     * 

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); @@ -628,7 +602,7 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass * .start(new BaseCallback>() { * {@literal@}Override * public void onSuccess(Map payload) {} - *

+ * * {@literal@}Override * public void onFailure(Auth0Exception error) {} * }); diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 86105f64..1c907a42 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -868,51 +868,7 @@ public void shouldGetNewIdTokenWithRefreshTokenSync() throws Exception { assertThat(delegation, is(notNullValue())); } - - @Test - public void shouldGetCustomizedDelegationRequestWithRefreshToken() throws Exception { - mockAPI.willReturnNewIdToken(); - - final MockBaseCallback> callback = new MockBaseCallback<>(); - client.delegationWithRefreshToken(REFRESH_TOKEN, "custom_api_type") - .setScope("custom_scope") - .setTarget("custom_target") - .start(callback); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/delegation")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("api_type", "custom_api_type")); - assertThat(body, hasEntry("scope", "custom_scope")); - assertThat(body, hasEntry("target", "custom_target")); - assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); - } - - @Test - public void shouldGetCustomizedDelegationRequestWithRefreshTokenSync() throws Exception { - mockAPI.willReturnNewIdToken(); - - client - .delegationWithRefreshToken(REFRESH_TOKEN, "custom_api_type") - .setScope("custom_scope") - .setTarget("custom_target") - .execute(); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/delegation")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_JWT)); - assertThat(body, hasEntry("client_id", CLIENT_ID)); - assertThat(body, hasEntry("api_type", "custom_api_type")); - assertThat(body, hasEntry("scope", "custom_scope")); - assertThat(body, hasEntry("target", "custom_target")); - assertThat(body, hasEntry("refresh_token", REFRESH_TOKEN)); - } - + @Test public void shouldUnlinkAccount() throws Exception { mockAPI.willReturnSuccessfulUnlinkAccount(); From f3ba3d131c47a38a60d7c411205f76471c0333f2 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Thu, 17 Mar 2016 10:36:39 -0300 Subject: [PATCH 61/89] Make protected method private --- .../AuthenticationAPIClient.java | 2 +- .../AuthenticationAPIClientTest.java | 99 ------------------- 2 files changed, 1 insertion(+), 100 deletions(-) diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 1b26c5a8..7fcb87dd 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -667,7 +667,7 @@ public ProfileRequest getProfileAfter(AuthenticationRequest authenticationReques return new ProfileRequest(authenticationRequest, profileRequest); } - protected AuthenticationRequest loginWithResourceOwner(Map parameters) { + private AuthenticationRequest loginWithResourceOwner(Map parameters) { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(OAUTH_PATH) .addPathSegment(RESOURCE_OWNER_PATH) diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 1c907a42..266bb727 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -65,7 +65,6 @@ public class AuthenticationAPIClientTest { private static final String CLIENT_ID = "CLIENTID"; private static final String DOMAIN = "samples.auth0.com"; - private static final String CONNECTION = "DB"; private static final String USERNAME_PASSWORD_AUTHENTICATION = "Username-Password-Authentication"; private static final String PASSWORD = "123123123"; private static final String SUPPORT_AUTH0_COM = "support@auth0.com"; @@ -101,104 +100,6 @@ public void shouldCreateClientWithAccountInfo() throws Exception { assertThat(client.getBaseURL(), equalTo("https://samples.auth0.com")); } - @Test - public void shouldLoginWithResourceOwner() throws Exception { - mockAPI.willReturnSuccessfulLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - final Map parameters = ParameterBuilder.newAuthenticationBuilder() - .setConnection("DB") - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", SUPPORT_AUTH0_COM) - .set("password", "notapassword") - .setScope(ParameterBuilder.SCOPE_OPENID) - .asDictionary(); - client - .loginWithResourceOwner(parameters) - .start(callback); - - assertThat(callback, hasPayloadOfType(Credentials.class)); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/ro")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "DB")); - assertThat(body, hasEntry("grant_type", "password")); - assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); - assertThat(body, hasEntry("password", "notapassword")); - assertThat(body, hasEntry("scope", OPENID)); - } - - @Test - public void shouldLoginWithResourceOwnerSync() throws Exception { - mockAPI.willReturnSuccessfulLogin(); - - final Map parameters = ParameterBuilder.newAuthenticationBuilder() - .setConnection("DB") - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", SUPPORT_AUTH0_COM) - .set("password", "notapassword") - .setScope(ParameterBuilder.SCOPE_OPENID) - .asDictionary(); - - final Credentials credentials = client - .loginWithResourceOwner(parameters) - .execute(); - - assertThat(credentials, is(notNullValue())); - - final RecordedRequest request = mockAPI.takeRequest(); - assertThat(request.getPath(), equalTo("/oauth/ro")); - - Map body = bodyFromRequest(request); - assertThat(body, hasEntry("connection", "DB")); - assertThat(body, hasEntry("grant_type", "password")); - assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM)); - assertThat(body, hasEntry("password", "notapassword")); - assertThat(body, hasEntry("scope", OPENID)); - } - - @Test - public void shouldFailLoginWithResourceOwner() throws Exception { - mockAPI.willReturnFailedLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - final Map parameters = ParameterBuilder.newAuthenticationBuilder() - .setConnection(CONNECTION) - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", SUPPORT_AUTH0_COM) - .set("password", "notapassword") - .asDictionary(); - client - .loginWithResourceOwner(parameters) - .start(callback); - - assertThat(callback, hasNoPayloadOfType(Credentials.class)); - } - - @Test - public void shouldFailLoginWithResourceOwnerSync() throws Exception { - mockAPI.willReturnFailedLogin(); - final MockBaseCallback callback = new MockBaseCallback<>(); - - final Map parameters = ParameterBuilder.newAuthenticationBuilder() - .setConnection(CONNECTION) - .setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD) - .set("username", SUPPORT_AUTH0_COM) - .set("password", "notapassword") - .asDictionary(); - - Exception exception = null; - try { - client.loginWithResourceOwner(parameters).execute(); - } catch (Auth0Exception e) { - exception = e; - } - - assertThat(exception, is(notNullValue())); - } - @Test public void shouldLoginWithUserAndPassword() throws Exception { mockAPI From 8b647b8bcc3fe51ec170d5db379a976e8aab27eb Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Thu, 17 Mar 2016 11:44:43 -0300 Subject: [PATCH 62/89] Some rename of classes and more javadoc --- lib/src/main/java/com/auth0/Auth0.java | 27 +++++------- .../AuthenticationAPIClient.java | 10 ++--- .../authentication/ParameterBuilder.java | 44 +++++++++---------- .../authentication/PasswordlessType.java | 23 ++++++++-- .../auth0/authentication/SignUpRequest.java | 17 ++++--- .../internal/BaseAuthenticationRequest.java | 11 +---- .../{ => request}/internal/BaseRequest.java | 2 +- .../internal/JsonRequestBodyBuilder.java | 2 +- .../internal/RequestFactory.java | 6 +-- .../{ => request}/internal/SimpleRequest.java | 2 +- .../{ => request}/internal/VoidRequest.java | 2 +- .../{BaseMetrics.java => BaseTelemetry.java} | 4 +- .../util/{Metrics.java => Telemetry.java} | 2 +- lib/src/test/java/com/auth0/Auth0Test.java | 8 ++++ .../AuthenticationAPIClientTest.java | 8 ++-- .../internal/BaseRequestTest.java | 2 +- ...etricsTest.java => BaseTelemetryTest.java} | 12 ++--- 17 files changed, 97 insertions(+), 85 deletions(-) rename lib/src/main/java/com/auth0/{ => request}/internal/BaseAuthenticationRequest.java (86%) rename lib/src/main/java/com/auth0/{ => request}/internal/BaseRequest.java (99%) rename lib/src/main/java/com/auth0/{ => request}/internal/JsonRequestBodyBuilder.java (98%) rename lib/src/main/java/com/auth0/{ => request}/internal/RequestFactory.java (97%) rename lib/src/main/java/com/auth0/{ => request}/internal/SimpleRequest.java (99%) rename lib/src/main/java/com/auth0/{ => request}/internal/VoidRequest.java (98%) rename lib/src/main/java/com/auth0/util/{BaseMetrics.java => BaseTelemetry.java} (90%) rename lib/src/main/java/com/auth0/util/{Metrics.java => Telemetry.java} (87%) rename lib/src/test/java/com/auth0/{ => request}/internal/BaseRequestTest.java (98%) rename lib/src/test/java/com/auth0/util/{BaseMetricsTest.java => BaseTelemetryTest.java} (62%) diff --git a/lib/src/main/java/com/auth0/Auth0.java b/lib/src/main/java/com/auth0/Auth0.java index f2a5b737..d28e3122 100644 --- a/lib/src/main/java/com/auth0/Auth0.java +++ b/lib/src/main/java/com/auth0/Auth0.java @@ -25,8 +25,8 @@ package com.auth0; import com.auth0.authentication.AuthenticationAPIClient; -import com.auth0.util.BaseMetrics; -import com.auth0.util.Metrics; +import com.auth0.util.BaseTelemetry; +import com.auth0.util.Telemetry; import com.squareup.okhttp.HttpUrl; /** @@ -53,7 +53,7 @@ public class Auth0 { private final String clientId; private final String domainUrl; private final String configurationUrl; - private Metrics metrics; + private Telemetry telemetry; /** * Creates a new object using clientId & domain @@ -76,8 +76,8 @@ public Auth0(String clientId, String domain, String configurationDomain) { this.clientId = clientId; this.domainUrl = ensureUrlString(domain); this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl); - this.metrics = new BaseMetrics(); - this.metrics.usingLibrary(Auth0.NAME, Auth0.VERSION); + this.telemetry = new BaseTelemetry(); + this.telemetry.usingLibrary(Auth0.NAME, Auth0.VERSION); } /** @@ -119,22 +119,17 @@ public String getAuthorizeUrl() { } /** - * @return Auth0 metrics sent in every requests + * @return Auth0 telemetry info sent in every request */ - public Metrics getMetrics() { - return metrics; + public Telemetry getTelemetry() { + return telemetry; } /** - * Define what metrics are sent to Auth0 on every request. - * @param metrics to send or nil to send nothing + * Avoid sending telemetry in every request to Auth0 */ - public void setMetrics(Metrics metrics) { - if (metrics == null) { - this.metrics = new BaseMetrics(); - } else { - this.metrics = metrics; - } + public void doNotSendTelemetry() { + this.telemetry = null; } private String resolveConfiguration(String configurationDomain, String domainUrl) { diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index 7fcb87dd..d3cfaf61 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -29,11 +29,11 @@ import com.auth0.authentication.result.DatabaseUser; import com.auth0.authentication.result.Delegation; import com.auth0.authentication.result.UserProfile; -import com.auth0.internal.RequestFactory; +import com.auth0.request.internal.RequestFactory; import com.auth0.request.AuthenticationRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; -import com.auth0.util.Metrics; +import com.auth0.util.Telemetry; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -103,9 +103,9 @@ private AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper m this.client = client; this.mapper = mapper; this.factory = new RequestFactory(); - final Metrics metrics = auth0.getMetrics(); - if (metrics != null) { - factory.setClientInfo(metrics.getValue()); + final Telemetry telemetry = auth0.getTelemetry(); + if (telemetry != null) { + factory.setClientInfo(telemetry.getValue()); } } diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java index 8463bb25..212a2107 100644 --- a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -31,14 +31,28 @@ import java.util.Map; /** - * Builder class for Auth API parameters. + * Builder for Auth0 Authentication API parameters + * + * You can build your parameters like this + *


+ *     Map parameters = ParameterBuilder.newBuilder()
+ *                                                      .setClientId("{CLIENT_ID}")
+ *                                                      .setConnection("{CONNECTION}")
+ *                                                      .set("{PARAMETER_NAME}", "{PARAMETER_VALUE}")
+ *                                                      .asDictionary();
+ * 
+ * + * @see ParameterBuilder#newBuilder() + * @see ParameterBuilder#newAuthenticationBuilder() */ public class ParameterBuilder { public static final String GRANT_TYPE_PASSWORD = "password"; public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + public static final String SCOPE_OPENID = "openid"; public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access"; + public static final String ID_TOKEN_KEY = "id_token"; public static final String SCOPE_KEY = "scope"; public static final String REFRESH_TOKEN_KEY = "refresh_token"; @@ -51,11 +65,6 @@ public class ParameterBuilder { private Map parameters; - /** - * Creates a new builder with default parameters - * - * @param parameters default parameters - */ private ParameterBuilder(Map parameters) { CheckHelper.checkArgument(parameters != null, "Must provide non-null parameters"); this.parameters = new HashMap<>(parameters); @@ -128,17 +137,7 @@ public ParameterBuilder setAccessToken(String accessToken) { * @return itself */ public ParameterBuilder setSend(PasswordlessType passwordlessType) { - switch (passwordlessType) { - default: - case CODE: - return set(SEND_KEY, "code"); - case LINK: - return set(SEND_KEY, "link"); - case LINK_ANDROID: - return set(SEND_KEY, "link_android"); - case LINK_IOS: - return set(SEND_KEY, "link_ios"); - } + return set(SEND_KEY, passwordlessType.getValue()); } /** @@ -179,14 +178,14 @@ public ParameterBuilder clearAll() { /** * Create a {@link Map} with all the parameters * - * @return an unmodifiable map with the parameters + * @return all parameters added previously as a {@link Map} */ public Map asDictionary() { return Collections.unmodifiableMap(new HashMap<>(this.parameters)); } /** - * Creates a new instance of the builder with default values + * Creates a new instance of the builder using default values for login request, e.g. 'openid' for scope. * * @return a new builder */ @@ -196,7 +195,8 @@ public static ParameterBuilder newAuthenticationBuilder() { } /** - * Creates a new instance of the builder without any default values + * Creates a new instance of the builder. + * This builder wont have any default values * * @return a new builder */ @@ -205,9 +205,9 @@ public static ParameterBuilder newBuilder() { } /** - * Creates a new instance of the builder with parameters. + * Creates a new instance of the builder from some initial parameters. * - * @param parameters default parameters + * @param parameters initial parameters * @return a new builder */ public static ParameterBuilder newBuilder(Map parameters) { diff --git a/lib/src/main/java/com/auth0/authentication/PasswordlessType.java b/lib/src/main/java/com/auth0/authentication/PasswordlessType.java index 124d071b..eaf57560 100644 --- a/lib/src/main/java/com/auth0/authentication/PasswordlessType.java +++ b/lib/src/main/java/com/auth0/authentication/PasswordlessType.java @@ -25,11 +25,28 @@ package com.auth0.authentication; /** - * An enum with all passwordless login types available in Auth0 + * Valid types of passwordless flows in Auth0 */ public enum PasswordlessType { - LINK, + /** + * Sends a link used to login + */ + LINK_WEB, LINK_ANDROID, LINK_IOS, - CODE + CODE; + + public String getValue() { + switch (this) { + default: + case CODE: + return "code"; + case LINK_WEB: + return "link"; + case LINK_ANDROID: + return "link_android"; + case LINK_IOS: + return "link_ios"; + } + } } diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java index 18f775c0..43ef465e 100644 --- a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/lib/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -29,13 +29,12 @@ import com.auth0.authentication.result.DatabaseUser; import com.auth0.callback.BaseCallback; import com.auth0.request.AuthenticationRequest; -import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; import java.util.Map; /** - * Represent a request to create a user + log in + * Represent a request that creates a user in a Auth0 Database connection and then logs in. */ public class SignUpRequest implements Request { @@ -48,8 +47,8 @@ public class SignUpRequest implements Request { } /** - * Add additional parameters for create user request - * @param parameters as a non-null dictionary + * Add additional parameters sent when creating a using. + * @param parameters sent with the request and must be non-null * @return itself */ public SignUpRequest addSignUpParameters(Map parameters) { @@ -58,9 +57,10 @@ public SignUpRequest addSignUpParameters(Map parameters) { } /** - * Add additional parameters for login request - * @param parameters as a non-null dictionary + * Add additional parameters sent when logging the user in + * @param parameters sent with the request and must be non-null * @return itself + * @see ParameterBuilder */ public SignUpRequest addAuthenticationParameters(Map parameters) { authenticationRequest.addAuthenticationParameters(parameters); @@ -68,7 +68,7 @@ public SignUpRequest addAuthenticationParameters(Map parameters) } /** - * Set the scope used to authenticate the user + * Set the scope used to login the user * @param scope value * @return itself */ @@ -97,8 +97,7 @@ public void start(final BaseCallback callback) { signUpRequest.start(new BaseCallback() { @Override public void onSuccess(final DatabaseUser user) { - authenticationRequest - .start(callback); + authenticationRequest.start(callback); } @Override diff --git a/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java b/lib/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java similarity index 86% rename from lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java rename to lib/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java index c1182854..34e9501d 100644 --- a/lib/src/main/java/com/auth0/internal/BaseAuthenticationRequest.java +++ b/lib/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java @@ -1,4 +1,4 @@ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.authentication.result.Credentials; import com.auth0.request.AuthenticationRequest; @@ -14,19 +14,12 @@ import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_KEY; import static com.auth0.authentication.ParameterBuilder.SCOPE_KEY; -/** - * Created by hernan on 3/16/16. - */ -public class BaseAuthenticationRequest extends SimpleRequest implements AuthenticationRequest { +class BaseAuthenticationRequest extends SimpleRequest implements AuthenticationRequest { public BaseAuthenticationRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod, Class clazz) { super(url, client, mapper, httpMethod, clazz); } - public BaseAuthenticationRequest(HttpUrl url, OkHttpClient client, ObjectMapper mapper, String httpMethod) { - super(url, client, mapper, httpMethod); - } - /** * Sets the 'grant_type' parameter * diff --git a/lib/src/main/java/com/auth0/internal/BaseRequest.java b/lib/src/main/java/com/auth0/request/internal/BaseRequest.java similarity index 99% rename from lib/src/main/java/com/auth0/internal/BaseRequest.java rename to lib/src/main/java/com/auth0/request/internal/BaseRequest.java index e8b9eb69..5cfe181e 100644 --- a/lib/src/main/java/com/auth0/internal/BaseRequest.java +++ b/lib/src/main/java/com/auth0/request/internal/BaseRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.APIException; import com.auth0.Auth0Exception; diff --git a/lib/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java b/lib/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java similarity index 98% rename from lib/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java rename to lib/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java index a15992ed..9a9a9608 100644 --- a/lib/src/main/java/com/auth0/internal/JsonRequestBodyBuilder.java +++ b/lib/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.RequestBodyBuildException; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/lib/src/main/java/com/auth0/internal/RequestFactory.java b/lib/src/main/java/com/auth0/request/internal/RequestFactory.java similarity index 97% rename from lib/src/main/java/com/auth0/internal/RequestFactory.java rename to lib/src/main/java/com/auth0/request/internal/RequestFactory.java index 48359cac..291a409d 100644 --- a/lib/src/main/java/com/auth0/internal/RequestFactory.java +++ b/lib/src/main/java/com/auth0/request/internal/RequestFactory.java @@ -22,13 +22,13 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.authentication.result.Credentials; import com.auth0.request.AuthenticationRequest; import com.auth0.request.AuthorizableRequest; import com.auth0.request.ParameterizableRequest; -import com.auth0.util.Metrics; +import com.auth0.util.Telemetry; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.OkHttpClient; @@ -105,7 +105,7 @@ public ParameterizableRequest DELETE(HttpUrl url, OkHttpClient client, Ob private void addMetrics(ParameterizableRequest request) { if (this.clientInfo != null) { - request.addHeader(Metrics.HEADER_NAME, this.clientInfo); + request.addHeader(Telemetry.HEADER_NAME, this.clientInfo); } if (this.userAgent!= null) { request.addHeader("User-Agent", this.userAgent); diff --git a/lib/src/main/java/com/auth0/internal/SimpleRequest.java b/lib/src/main/java/com/auth0/request/internal/SimpleRequest.java similarity index 99% rename from lib/src/main/java/com/auth0/internal/SimpleRequest.java rename to lib/src/main/java/com/auth0/request/internal/SimpleRequest.java index abbe55a8..0f432eae 100644 --- a/lib/src/main/java/com/auth0/internal/SimpleRequest.java +++ b/lib/src/main/java/com/auth0/request/internal/SimpleRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.Auth0Exception; import com.auth0.APIException; diff --git a/lib/src/main/java/com/auth0/internal/VoidRequest.java b/lib/src/main/java/com/auth0/request/internal/VoidRequest.java similarity index 98% rename from lib/src/main/java/com/auth0/internal/VoidRequest.java rename to lib/src/main/java/com/auth0/request/internal/VoidRequest.java index 74edb6d2..a23d88b0 100644 --- a/lib/src/main/java/com/auth0/internal/VoidRequest.java +++ b/lib/src/main/java/com/auth0/request/internal/VoidRequest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.Auth0Exception; import com.auth0.APIException; diff --git a/lib/src/main/java/com/auth0/util/BaseMetrics.java b/lib/src/main/java/com/auth0/util/BaseTelemetry.java similarity index 90% rename from lib/src/main/java/com/auth0/util/BaseMetrics.java rename to lib/src/main/java/com/auth0/util/BaseTelemetry.java index 768401d3..ae3c7064 100644 --- a/lib/src/main/java/com/auth0/util/BaseMetrics.java +++ b/lib/src/main/java/com/auth0/util/BaseTelemetry.java @@ -6,11 +6,11 @@ import java.util.HashMap; import java.util.Map; -public class BaseMetrics implements Metrics { +public class BaseTelemetry implements Telemetry { private final Map values; - public BaseMetrics() { + public BaseTelemetry() { this.values = new HashMap<>(); } diff --git a/lib/src/main/java/com/auth0/util/Metrics.java b/lib/src/main/java/com/auth0/util/Telemetry.java similarity index 87% rename from lib/src/main/java/com/auth0/util/Metrics.java rename to lib/src/main/java/com/auth0/util/Telemetry.java index f60679c2..c49b1d3d 100644 --- a/lib/src/main/java/com/auth0/util/Metrics.java +++ b/lib/src/main/java/com/auth0/util/Telemetry.java @@ -1,6 +1,6 @@ package com.auth0.util; -public interface Metrics { +public interface Telemetry { String NAME_KEY = "name"; String VERSION_KEY = "version"; String HEADER_NAME = "Auth0-Client"; diff --git a/lib/src/test/java/com/auth0/Auth0Test.java b/lib/src/test/java/com/auth0/Auth0Test.java index 8a732815..361717dc 100644 --- a/lib/src/test/java/com/auth0/Auth0Test.java +++ b/lib/src/test/java/com/auth0/Auth0Test.java @@ -31,6 +31,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; public class Auth0Test { @@ -104,4 +105,11 @@ public void shouldReturnAuthorizeUrl() throws Exception { Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); assertThat(auth0.getAuthorizeUrl(), equalTo("https://samples.auth0.com/authorize")); } + + @Test + public void shouldNotReturnTelemetryWhenExplicitlyDisabledThem() throws Exception { + Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN); + auth0.doNotSendTelemetry(); + assertThat(auth0.getTelemetry(), is(nullValue())); + } } \ No newline at end of file diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java index 266bb727..3cc630dc 100644 --- a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java +++ b/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java @@ -898,7 +898,7 @@ public void shouldSendEmailLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_WEB) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -917,7 +917,7 @@ public void shouldSendEmailLink() throws Exception { public void shouldSendEmailLinkSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK) + client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.LINK_WEB) .execute(); final RecordedRequest request = mockAPI.takeRequest(); @@ -1046,7 +1046,7 @@ public void shouldSendSMSLink() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); final MockBaseCallback callback = new MockBaseCallback<>(); - client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK) + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_WEB) .start(callback); final RecordedRequest request = mockAPI.takeRequest(); @@ -1065,7 +1065,7 @@ public void shouldSendSMSLink() throws Exception { public void shouldSendSMSLinkSync() throws Exception { mockAPI.willReturnSuccessfulPasswordlessStart(); - client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK) + client.passwordlessWithSMS("+1123123123", PasswordlessType.LINK_WEB) .execute(); final RecordedRequest request = mockAPI.takeRequest(); diff --git a/lib/src/test/java/com/auth0/internal/BaseRequestTest.java b/lib/src/test/java/com/auth0/request/internal/BaseRequestTest.java similarity index 98% rename from lib/src/test/java/com/auth0/internal/BaseRequestTest.java rename to lib/src/test/java/com/auth0/request/internal/BaseRequestTest.java index 8ef942b1..8ee2683c 100644 --- a/lib/src/test/java/com/auth0/internal/BaseRequestTest.java +++ b/lib/src/test/java/com/auth0/request/internal/BaseRequestTest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package com.auth0.internal; +package com.auth0.request.internal; import com.auth0.Auth0Exception; diff --git a/lib/src/test/java/com/auth0/util/BaseMetricsTest.java b/lib/src/test/java/com/auth0/util/BaseTelemetryTest.java similarity index 62% rename from lib/src/test/java/com/auth0/util/BaseMetricsTest.java rename to lib/src/test/java/com/auth0/util/BaseTelemetryTest.java index d8e5bdc8..e84669ac 100644 --- a/lib/src/test/java/com/auth0/util/BaseMetricsTest.java +++ b/lib/src/test/java/com/auth0/util/BaseTelemetryTest.java @@ -8,23 +8,23 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; -public class BaseMetricsTest { +public class BaseTelemetryTest { - private BaseMetrics metrics; + private BaseTelemetry telemetry; @Before public void setUp() throws Exception { - metrics = new BaseMetrics(); + telemetry = new BaseTelemetry(); } @Test public void shouldReturnBase64() throws Exception { - metrics.usingLibrary("auth0-java", "1.0.0"); - assertThat(metrics.getValue(), is(notNullValue())); + telemetry.usingLibrary("auth0-java", "1.0.0"); + assertThat(telemetry.getValue(), is(notNullValue())); } @Test public void shouldReturnNullWhenNoInfoIsProvided() throws Exception { - assertThat(metrics.getValue(), is(nullValue())); + assertThat(telemetry.getValue(), is(nullValue())); } } \ No newline at end of file From 8b8d2ea1983235110b4721bde66c34ac4152201c Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Thu, 17 Mar 2016 12:43:01 -0300 Subject: [PATCH 63/89] Rename default db name setter. First draft of README and LICENSE. --- LICENSE | 2 +- README.md | 102 +++++++++++++++++- lib/src/main/java/com/auth0/Auth0.java | 23 +++- .../AuthenticationAPIClient.java | 30 ++---- lib/src/test/java/com/auth0/Auth0Test.java | 2 +- 5 files changed, 133 insertions(+), 26 deletions(-) diff --git a/LICENSE b/LICENSE index a7f9e41d..5836564e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Auth0 +Copyright (c) 2016 Auth0, Inc. (http://auth0.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index a1f4774d..b8a5c6e2 100644 --- a/README.md +++ b/README.md @@ -1 +1,101 @@ -# auth0-api-java +# Auth0 Java + +Java client library for the [Auth0](https://auth0.com) platform. + +## Download + +Get Auth0 Java via Maven: + +```xml + + com.auth0 + auth0-java + 0.0.1 + +``` + +or Gradle: + +```gradle +compile 'com.auth0:auth0-java:0.0.1' +``` + +## Usage + +First with your Auth0 account information + +```java +Auth0 auth0 = new Auth0("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}"); +``` + +and then ask `Auth0` object for the Authentication API Client + +```java +AuthenticationAPIClient client = auth0.newAuthenticationAPIClient(); +``` + +> Currently we only have a Authentication API Client, in future version we'll start adding Management API Client and methods. + +### Authentication API + +#### Making a request + +Asynchronously + +```java +Auth0 auth0 = new Auth0("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}"); +AuthenticationAPIClient client = auth0.newAuthenticationAPIClient(); + +client.login("{username or email}", "{password}") + .setConnection("{database connection name}") + .start(new BaseCallback() { + Override + public void onSuccess(Credentials payload) { } + + Override + public void onFailure(Auth0Exception error) { } + }); +``` + +Synchronously + +```java +Auth0 auth0 = new Auth0("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}"); +AuthenticationAPIClient client = auth0.newAuthenticationAPIClient(); + +Credentials credentials = client.login("{username or email}", "{password}") + .setConnection("{database connection name}") + .execute(); +``` + +## Documentation + +For more information about [auth0](http://auth0.com) check our [documentation page](http://docs.auth0.com/). + +## What is Auth0? + +Auth0 helps you to: + +* Add authentication with [multiple authentication sources](https://docs.auth0.com/identityproviders), either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others**, or enterprise identity systems like **Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider**. +* Add authentication through more traditional **[username/password databases](https://docs.auth0.com/mysql-connection-tutorial)**. +* Add support for **[linking different user accounts](https://docs.auth0.com/link-accounts)** with the same user. +* Support for generating signed [Json Web Tokens](https://docs.auth0.com/jwt) to call your APIs and **flow the user identity** securely. +* Analytics of how, when and where users are logging in. +* Pull data from other sources and add it to the user profile, through [JavaScript rules](https://docs.auth0.com/rules). + +## Create a free Auth0 Account + +1. Go to [Auth0](https://auth0.com) and click Sign Up. +2. Use Google, GitHub or Microsoft Account to login. + +## Issue Reporting + +If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues. + +## Author + +[Auth0](auth0.com) + +## License + +This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info. \ No newline at end of file diff --git a/lib/src/main/java/com/auth0/Auth0.java b/lib/src/main/java/com/auth0/Auth0.java index d28e3122..71f2efa2 100644 --- a/lib/src/main/java/com/auth0/Auth0.java +++ b/lib/src/main/java/com/auth0/Auth0.java @@ -51,6 +51,7 @@ public class Auth0 { private static final String DOT_AUTH0_DOT_COM = ".auth0.com"; private final String clientId; + private final String clientSecret; private final String domainUrl; private final String configurationUrl; private Telemetry telemetry; @@ -61,7 +62,16 @@ public class Auth0 { * @param domain of your Auth0 account */ public Auth0(String clientId, String domain) { - this(clientId, domain, null); + this(clientId, null, domain, null); + } + + /** + * Creates a new object using clientId & domain + * @param clientId of your Auth0 application + * @param domain of your Auth0 account + */ + public Auth0(String clientId, String clientSecret, String domain) { + this(clientId, clientSecret, domain, null); } /** @@ -69,11 +79,13 @@ public Auth0(String clientId, String domain) { * Useful when using a on-premise auth0 server that is not in the public cloud, * otherwise we recommend using the constructor {@link #Auth0(String, String)} * @param clientId of your Auth0 application + * @param clientSecret of your Auth0 application. It can be null, specially if used for an Android application * @param domain of your Auth0 account * @param configurationDomain where Auth0's configuration will be fetched. By default is Auth0 public cloud */ - public Auth0(String clientId, String domain, String configurationDomain) { + public Auth0(String clientId, String clientSecret, String domain, String configurationDomain) { this.clientId = clientId; + this.clientSecret = clientSecret; this.domainUrl = ensureUrlString(domain); this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl); this.telemetry = new BaseTelemetry(); @@ -94,6 +106,13 @@ public String getDomainUrl() { return domainUrl; } + /** + * @return your Auth0 account client secret or null + */ + public String getClientSecret() { + return clientSecret; + } + /** * @return your account configuration url */ diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index d3cfaf61..f81a45c0 100644 --- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -75,7 +75,7 @@ public class AuthenticationAPIClient { private final ObjectMapper mapper; private final RequestFactory factory; - private String defaultDbConnection = DEFAULT_DB_CONNECTION; + private String defaultDatabaseConnection = DEFAULT_DB_CONNECTION; /** * Creates a new API client instance providing Auth0 account info. @@ -86,18 +86,6 @@ public AuthenticationAPIClient(Auth0 auth0) { this(auth0, new OkHttpClient(), new ObjectMapper()); } - /** - * Creates a new API client instance providing Auth API and Configuration Urls different than the default. (Useful for on premise deploys). - * - * @param clientID Your application clientID. - * @param baseURL Auth0's auth API endpoint - * @param configurationURL Auth0's endpoint where App info can be retrieved. - */ - @SuppressWarnings("unused") - public AuthenticationAPIClient(String clientID, String baseURL, String configurationURL) { - this(new Auth0(clientID, baseURL, configurationURL)); - } - private AuthenticationAPIClient(Auth0 auth0, OkHttpClient client, ObjectMapper mapper) { this.auth0 = auth0; this.client = client; @@ -127,12 +115,12 @@ public void setUserAgent(String userAgent) { } /** - * Set the default DB connection name used. By default is 'Username-Password-Authentication' + * Set the default Auth0 database connection name used. By default is 'Username-Password-Authentication' * - * @param defaultDbConnection name to use on every login with DB connection + * @param defaultDatabaseConnection name to use on every login with DB connection */ - public void setDefaultDbConnection(String defaultDbConnection) { - this.defaultDbConnection = defaultDbConnection; + public void setDefaultDatabaseConnection(String defaultDatabaseConnection) { + this.defaultDatabaseConnection = defaultDatabaseConnection; } /** @@ -140,7 +128,7 @@ public void setDefaultDbConnection(String defaultDbConnection) { * Example usage: *

      * client.login("{username or email}", "{password}")
-     *      .setConnection("second-database")
+     *      .setConnection("{database connection name}")
      *      .start(new BaseCallback() {
      *          {@literal@}Override
      *          public void onSuccess(Credentials payload) { }
@@ -308,7 +296,7 @@ public DatabaseConnectionRequest createUser(String email, String p
                 .set(USERNAME_KEY, username)
                 .set(EMAIL_KEY, email)
                 .set(PASSWORD_KEY, password)
-                .setConnection(defaultDbConnection)
+                .setConnection(defaultDatabaseConnection)
                 .setClientId(getClientId())
                 .asDictionary();
         final ParameterizableRequest request = factory.POST(url, client, mapper, DatabaseUser.class)
@@ -418,7 +406,7 @@ public DatabaseConnectionRequest requestChangePassword(String email) {
         final Map parameters = ParameterBuilder.newBuilder()
                 .set(EMAIL_KEY, email)
                 .setClientId(getClientId())
-                .setConnection(defaultDbConnection)
+                .setConnection(defaultDatabaseConnection)
                 .asDictionary();
         final ParameterizableRequest request = factory.POST(url, client, mapper)
                 .addParameters(parameters);
@@ -675,7 +663,7 @@ private AuthenticationRequest loginWithResourceOwner(Map paramet
 
         final Map requestParameters = ParameterBuilder.newBuilder()
                 .setClientId(getClientId())
-                .setConnection(defaultDbConnection)
+                .setConnection(defaultDatabaseConnection)
                 .addAll(parameters)
                 .asDictionary();
         return factory.authenticationPOST(url, client, mapper)
diff --git a/lib/src/test/java/com/auth0/Auth0Test.java b/lib/src/test/java/com/auth0/Auth0Test.java
index 361717dc..ce618d32 100644
--- a/lib/src/test/java/com/auth0/Auth0Test.java
+++ b/lib/src/test/java/com/auth0/Auth0Test.java
@@ -53,7 +53,7 @@ public void shouldBuildWithClientIdAndDomain() throws Exception {
 
     @Test
     public void shouldBuildWithConfigurationDomainToo() throws Exception {
-        Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN, CONFIG_DOMAIN_CUSTOM);
+        Auth0 auth0 = new Auth0(CLIENT_ID, null, DOMAIN, CONFIG_DOMAIN_CUSTOM);
         assertThat(auth0.getClientId(), equalTo(CLIENT_ID));
         assertThat(auth0.getDomainUrl(), equalTo("https://samples.auth0.com"));
         assertThat(auth0.getConfigurationUrl(), equalTo("https://config.mydomain.com"));

From 818d1e35c908dec70953bfe068a626362fec44fa Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Thu, 17 Mar 2016 13:36:18 -0300
Subject: [PATCH 64/89] Add android steps

---
 README.md | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/README.md b/README.md
index b8a5c6e2..6805e27c 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,22 @@ AuthenticationAPIClient client = auth0.newAuthenticationAPIClient();
 
 > Currently we only have a Authentication API Client, in future version we'll start adding Management API Client and methods.
 
+### Android
+
+You need to add the following to your `build.gradle` file:
+
+``` gradle
+android {
+
+    // Other config of your application
+    
+    packagingOptions {
+        exclude 'META-INF/LICENSE'
+        exclude 'META-INF/NOTICE'
+    }
+}
+```
+
 ### Authentication API
 
 #### Making a request

From 364229b8030a724064c00ccd46432f5f4aa3d2de Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Thu, 17 Mar 2016 13:45:05 -0300
Subject: [PATCH 65/89] Add build badge

---
 README.md | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 6805e27c..9cc11b3c 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
 # Auth0 Java
 
+[![Build status][travis-ci-badge]](travis-ci-url)
+
 Java client library for the [Auth0](https://auth0.com) platform.
 
 ## Download
@@ -114,4 +116,10 @@ If you have found a bug or if you have a feature request, please report them at
 
 ## License
 
-This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
\ No newline at end of file
+This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
+
+
+
+
+[travis-ci-badge]: https://travis-ci.org/auth0/auth0-api-java.svg?branch=master
+[tavis-ci-url]: https://travis-ci.org/auth0/auth0-api-java
\ No newline at end of file

From 0a2beca707c09120aa7c29ed08c78858663b7e31 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Thu, 17 Mar 2016 14:03:50 -0300
Subject: [PATCH 66/89] Add BuildConfig class

---
 lib/src/main/java/com/auth0/Auth0.java       | 11 +----------
 lib/src/main/java/com/auth0/BuildConfig.java | 16 ++++++++++++++++
 2 files changed, 17 insertions(+), 10 deletions(-)
 create mode 100644 lib/src/main/java/com/auth0/BuildConfig.java

diff --git a/lib/src/main/java/com/auth0/Auth0.java b/lib/src/main/java/com/auth0/Auth0.java
index 71f2efa2..29ae2754 100644
--- a/lib/src/main/java/com/auth0/Auth0.java
+++ b/lib/src/main/java/com/auth0/Auth0.java
@@ -38,15 +38,6 @@
  */
 public class Auth0 {
 
-    /**
-     * Version of auth0-java
-     */
-    public static final String VERSION = "1.0.0";
-    /**
-     * Name of the library auth0-java
-     */
-    public static final String NAME = "auth0-java";
-
     private static final String AUTH0_US_CDN_URL = "https://cdn.auth0.com";
     private static final String DOT_AUTH0_DOT_COM = ".auth0.com";
 
@@ -89,7 +80,7 @@ public Auth0(String clientId, String clientSecret, String domain, String configu
         this.domainUrl = ensureUrlString(domain);
         this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl);
         this.telemetry = new BaseTelemetry();
-        this.telemetry.usingLibrary(Auth0.NAME, Auth0.VERSION);
+        this.telemetry.usingLibrary(BuildConfig.NAME, BuildConfig.VERSION);
     }
 
     /**
diff --git a/lib/src/main/java/com/auth0/BuildConfig.java b/lib/src/main/java/com/auth0/BuildConfig.java
new file mode 100644
index 00000000..50e6ad77
--- /dev/null
+++ b/lib/src/main/java/com/auth0/BuildConfig.java
@@ -0,0 +1,16 @@
+package com.auth0;
+
+abstract class BuildConfig {
+
+    private BuildConfig() {};
+
+    /**
+     * Version of auth0-java
+     */
+    public static final String VERSION = "1.0.0";
+    /**
+     * Name of the library auth0-java
+     */
+    public static final String NAME = "auth0-java";
+
+}

From 78890c7ac0a33704f9a65e717f8ee835e25195d2 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Fri, 18 Mar 2016 11:18:46 -0300
Subject: [PATCH 67/89] Use git describe to infer version name

---
 build.gradle     |  1 -
 lib/build.gradle | 52 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)

diff --git a/build.gradle b/build.gradle
index 25a86166..27685e36 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,6 +1,5 @@
 allprojects {
     group = 'com.auth0'
-    version = '0.0.1-SNAPSHOT'
 
     repositories {
         jcenter()
diff --git a/lib/build.gradle b/lib/build.gradle
index 17e46290..3560a2be 100644
--- a/lib/build.gradle
+++ b/lib/build.gradle
@@ -14,3 +14,55 @@ dependencies {
     testCompile 'com.squareup.okhttp:mockwebserver:2.5.0'
     testCompile 'com.jayway.awaitility:awaitility:1.6.4'
 }
+
+def semver = defineVersion()
+version = semver.stringVersion
+
+jar {
+    baseName = "auth0"
+}
+
+logger.lifecycle("Using version ${version} for ${name}")
+
+def defineVersion() {
+    def current = describeGit(false)
+    def snapshot = current == null
+    if (snapshot) {
+        current = describeGit(snapshot, "0.0.1")
+    }
+    return new Semver(snapshot: snapshot, version: current)
+}
+
+def describeGit(boolean snapshot, String defaultValue = null) {
+    def arguments = ['describe', '--tags']
+    arguments.add(snapshot ? '--abbrev=0' : '--exact-match')
+    def stdout = new ByteArrayOutputStream()
+    def string = defaultValue
+    try {
+        def result = project.exec {
+            executable = 'git'
+            args = arguments
+            standardOutput = stdout
+        }
+
+        result.assertNormalExitValue()
+
+        if (stdout.toByteArray().length > 0) {
+            string = stdout.toString().replace("\n", "")
+        }
+    } catch(Exception e) {
+        logger.debug("Failed git describe command", e)
+    } finally {
+        stdout.close()
+    }
+    return string
+}
+
+class Semver {
+    def version
+    def snapshot
+
+    def getStringVersion() {
+        return snapshot ? version + "-SNAPSHOT" : version
+    }
+}
\ No newline at end of file

From c5d0a9fdd73dae933937fda01bee8ed07e9809c9 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Fri, 18 Mar 2016 11:29:38 -0300
Subject: [PATCH 68/89] Rename lib to auth0

---
 {lib => auth0}/build.gradle                   | 18 ++++-
 .../src/main/java/com/auth0/APIException.java |  0
 .../src/main/java/com/auth0/Auth0.java        |  0
 .../main/java/com/auth0/Auth0Exception.java   |  0
 .../src/main/java/com/auth0/BuildConfig.java  |  0
 .../com/auth0/RequestBodyBuildException.java  |  0
 .../AuthenticationAPIClient.java              | 72 +++++++++----------
 .../DatabaseConnectionRequest.java            |  0
 .../authentication/DelegationRequest.java     |  0
 .../authentication/ParameterBuilder.java      |  0
 .../authentication/PasswordlessType.java      |  0
 .../auth0/authentication/ProfileRequest.java  |  0
 .../auth0/authentication/SignUpRequest.java   |  0
 .../authentication/result/Authentication.java |  4 +-
 .../authentication/result/Credentials.java    |  0
 .../authentication/result/DatabaseUser.java   |  0
 .../authentication/result/Delegation.java     |  0
 .../authentication/result/UserIdentity.java   |  0
 .../authentication/result/UserProfile.java    |  0
 .../java/com/auth0/callback/BaseCallback.java |  0
 .../java/com/auth0/callback/Callback.java     |  0
 .../auth0/request/AuthenticationRequest.java  |  0
 .../auth0/request/AuthorizableRequest.java    |  0
 .../auth0/request/ParameterizableRequest.java |  0
 .../main/java/com/auth0/request/Request.java  |  0
 .../internal/BaseAuthenticationRequest.java   |  0
 .../auth0/request/internal/BaseRequest.java   |  0
 .../internal/JsonRequestBodyBuilder.java      |  0
 .../request/internal/RequestFactory.java      |  0
 .../auth0/request/internal/SimpleRequest.java |  0
 .../auth0/request/internal/VoidRequest.java   |  0
 .../src/main/java/com/auth0/util/Base64.java  |  0
 .../java/com/auth0/util/BaseTelemetry.java    |  0
 .../main/java/com/auth0/util/CheckHelper.java |  0
 .../main/java/com/auth0/util/Telemetry.java   |  0
 .../src/test/java/com/auth0/Auth0Test.java    |  0
 .../test/java/com/auth0/UserProfileTest.java  |  0
 .../AuthenticationAPIClientTest.java          |  0
 .../authentication/ParameterBuilderTest.java  |  0
 .../request/internal/BaseRequestTest.java     |  0
 .../com/auth0/util/AuthenticationAPI.java     |  0
 .../com/auth0/util/BaseTelemetryTest.java     |  0
 .../java/com/auth0/util/CallbackMatcher.java  |  0
 .../java/com/auth0/util/MockBaseCallback.java |  0
 settings.gradle                               |  2 +-
 45 files changed, 55 insertions(+), 41 deletions(-)
 rename {lib => auth0}/build.gradle (86%)
 rename {lib => auth0}/src/main/java/com/auth0/APIException.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/Auth0.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/Auth0Exception.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/BuildConfig.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/RequestBodyBuildException.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java (95%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/DelegationRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/ParameterBuilder.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/PasswordlessType.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/ProfileRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/SignUpRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/Authentication.java (96%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/Credentials.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/DatabaseUser.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/Delegation.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/UserIdentity.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/authentication/result/UserProfile.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/callback/BaseCallback.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/callback/Callback.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/AuthenticationRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/AuthorizableRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/ParameterizableRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/Request.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/BaseRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/RequestFactory.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/SimpleRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/request/internal/VoidRequest.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/util/Base64.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/util/BaseTelemetry.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/util/CheckHelper.java (100%)
 rename {lib => auth0}/src/main/java/com/auth0/util/Telemetry.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/Auth0Test.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/UserProfileTest.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/authentication/ParameterBuilderTest.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/request/internal/BaseRequestTest.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/util/AuthenticationAPI.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/util/BaseTelemetryTest.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/util/CallbackMatcher.java (100%)
 rename {lib => auth0}/src/test/java/com/auth0/util/MockBaseCallback.java (100%)

diff --git a/lib/build.gradle b/auth0/build.gradle
similarity index 86%
rename from lib/build.gradle
rename to auth0/build.gradle
index 3560a2be..3b2c19f9 100644
--- a/lib/build.gradle
+++ b/auth0/build.gradle
@@ -18,11 +18,23 @@ dependencies {
 def semver = defineVersion()
 version = semver.stringVersion
 
-jar {
-    baseName = "auth0"
+logger.lifecycle("Using version ${version} for ${name}")
+
+
+task sourcesJar(type: Jar, dependsOn: classes) {
+    classifier = 'sources'
+    from sourceSets.main.allSource
 }
 
-logger.lifecycle("Using version ${version} for ${name}")
+task javadocJar(type: Jar, dependsOn: javadoc) {
+    classifier = 'javadoc'
+    from javadoc.destinationDir
+}
+
+artifacts {
+    archives sourcesJar
+    archives javadocJar
+}
 
 def defineVersion() {
     def current = describeGit(false)
diff --git a/lib/src/main/java/com/auth0/APIException.java b/auth0/src/main/java/com/auth0/APIException.java
similarity index 100%
rename from lib/src/main/java/com/auth0/APIException.java
rename to auth0/src/main/java/com/auth0/APIException.java
diff --git a/lib/src/main/java/com/auth0/Auth0.java b/auth0/src/main/java/com/auth0/Auth0.java
similarity index 100%
rename from lib/src/main/java/com/auth0/Auth0.java
rename to auth0/src/main/java/com/auth0/Auth0.java
diff --git a/lib/src/main/java/com/auth0/Auth0Exception.java b/auth0/src/main/java/com/auth0/Auth0Exception.java
similarity index 100%
rename from lib/src/main/java/com/auth0/Auth0Exception.java
rename to auth0/src/main/java/com/auth0/Auth0Exception.java
diff --git a/lib/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
similarity index 100%
rename from lib/src/main/java/com/auth0/BuildConfig.java
rename to auth0/src/main/java/com/auth0/BuildConfig.java
diff --git a/lib/src/main/java/com/auth0/RequestBodyBuildException.java b/auth0/src/main/java/com/auth0/RequestBodyBuildException.java
similarity index 100%
rename from lib/src/main/java/com/auth0/RequestBodyBuildException.java
rename to auth0/src/main/java/com/auth0/RequestBodyBuildException.java
diff --git a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java
similarity index 95%
rename from lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java
rename to auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java
index f81a45c0..a5129de4 100644
--- a/lib/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java
+++ b/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java
@@ -130,10 +130,10 @@ public void setDefaultDatabaseConnection(String defaultDatabaseConnection) {
      * client.login("{username or email}", "{password}")
      *      .setConnection("{database connection name}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Credentials payload) { }
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) { }
      *      });
      * 
@@ -158,10 +158,10 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { * client.loginWithOAuthAccessToken("{token}", "{connection name}") * .setConnection("second-database") * .start(new BaseCallback() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(Credentials payload) { } - * {@literal@}Override + * {@literal}Override * public void onFailure(Auth0Exception error) { } * }); *
@@ -192,10 +192,10 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn *

      * client.loginWithPhoneNumber("{phone number}", "{code}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Credentials payload) { }
 
-     *          {@literal@}@Override
+     *          {@literal}@Override
      *          public void onFailure(Auth0Exception error) { }
      *      });
      * 
@@ -221,10 +221,10 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver *

      * client.loginWithEmail("{email}", "{code}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Credentials payload) { }
 
-     *          {@literal@}@Override
+     *          {@literal}@Override
      *          public void onFailure(Auth0Exception error) { }
      *      });
      * 
@@ -250,10 +250,10 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod *

      * client.tokenInfo("{id_token}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(UserProfile payload) { }
 
-     *          {@literal@}@Override
+     *          {@literal}@Override
      *          public void onFailure(Auth0Exception error) { }
      *      });
      * 
@@ -273,10 +273,10 @@ public Request tokenInfo(String idToken) { * client.createUser("{email}", "{password}", "{username}") * .setConnection("{connection name}") * .start(new BaseCallback() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(DatabaseUser payload) { } * - * {@literal@}@Override + * {@literal}@Override * public void onFailure(Auth0Exception error) { } * }); *
@@ -311,10 +311,10 @@ public DatabaseConnectionRequest createUser(String email, String p * client.createUser("{email}", "{password}") * .setConnection("{connection name}") * .start(new BaseCallback() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(DatabaseUser payload) { } * - * {@literal@}@Override + * {@literal}@Override * public void onFailure(Auth0Exception error) { } * }); *
@@ -335,10 +335,10 @@ public DatabaseConnectionRequest createUser(String email, String p * client.signUp("{email}", "{password}", "{username}") * .setConnection("{connection name}") * .start(new BaseCallback() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(Credentials payload) {} * - * {@literal@}Override + * {@literal}Override * public void onFailure(Auth0Exception error) {} * }); *
@@ -362,10 +362,10 @@ public SignUpRequest signUp(String email, String password, String username) { * client.signUp("{email}", "{password}") * .setConnection("{connection name}") * .start(new BaseCallback() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(Credentials payload) {} * - * {@literal@}Override + * {@literal}Override * public void onFailure(Auth0Exception error) {} * }); *
@@ -386,10 +386,10 @@ public SignUpRequest signUp(String email, String password) { *

      * client.requestChangePassword("{email}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Void payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -419,10 +419,10 @@ public DatabaseConnectionRequest requestChangePassword(String email) { *

      * client.delegationWithIdToken("{id token}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Delegation payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -445,10 +445,10 @@ public DelegationRequest delegationWithIdToken(String idToken) { *

      * client.delegationWithRefreshToken("{refresh token}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Delegation payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -470,10 +470,10 @@ public DelegationRequest delegationWithRefreshToken(String refreshTo *

      * client.delegationWithIdToken("{id token}", "{app type, e.g. firebase}")
      *      .start(new BaseCallback>() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Map payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -496,10 +496,10 @@ public DelegationRequest> delegationWithIdToken(String idTok *

      * client.unlink("{auth0 user id}", "{user access token}")
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Void payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -529,10 +529,10 @@ public Request unlink(String userId, String accessToken) { *

      * client.passwordlessWithEmail("{email}", PasswordlessType.CODE)
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Void payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -558,10 +558,10 @@ public ParameterizableRequest passwordlessWithEmail(String email, Password *

      * client.passwordlessWithSms("{phone number}", PasswordlessType.CODE)
      *      .start(new BaseCallback() {
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onSuccess(Void payload) {}
      *
-     *          {@literal@}Override
+     *          {@literal}Override
      *          public void onFailure(Auth0Exception error) {}
      *      });
      * 
@@ -588,10 +588,10 @@ public ParameterizableRequest passwordlessWithSMS(String phoneNumber, Pass * client.delegation() * .addParameter("api_type", "firebase") * .start(new BaseCallback>() { - * {@literal@}Override + * {@literal}Override * public void onSuccess(Map payload) {} * - * {@literal@}Override + * {@literal}Override * public void onFailure(Auth0Exception error) {} * }); *
@@ -647,8 +647,8 @@ public ParameterizableRequest passwordless() { * Fetch the user's profile after it's authenticated by a login request. * If the login request fails, the returned request will fail * - * @param authenticationRequest that will authenticate a user with Auth0 and return a {@see Credentials} - * @return a {@see ProfileRequest} that first logins and the fetches the profile + * @param authenticationRequest that will authenticate a user with Auth0 and return a {@link Credentials} + * @return a {@link ProfileRequest} that first logins and the fetches the profile */ public ProfileRequest getProfileAfter(AuthenticationRequest authenticationRequest) { final ParameterizableRequest profileRequest = profileRequest(); diff --git a/lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java b/auth0/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java rename to auth0/src/main/java/com/auth0/authentication/DatabaseConnectionRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/DelegationRequest.java b/auth0/src/main/java/com/auth0/authentication/DelegationRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/DelegationRequest.java rename to auth0/src/main/java/com/auth0/authentication/DelegationRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/ParameterBuilder.java b/auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/ParameterBuilder.java rename to auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java diff --git a/lib/src/main/java/com/auth0/authentication/PasswordlessType.java b/auth0/src/main/java/com/auth0/authentication/PasswordlessType.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/PasswordlessType.java rename to auth0/src/main/java/com/auth0/authentication/PasswordlessType.java diff --git a/lib/src/main/java/com/auth0/authentication/ProfileRequest.java b/auth0/src/main/java/com/auth0/authentication/ProfileRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/ProfileRequest.java rename to auth0/src/main/java/com/auth0/authentication/ProfileRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/SignUpRequest.java b/auth0/src/main/java/com/auth0/authentication/SignUpRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/SignUpRequest.java rename to auth0/src/main/java/com/auth0/authentication/SignUpRequest.java diff --git a/lib/src/main/java/com/auth0/authentication/result/Authentication.java b/auth0/src/main/java/com/auth0/authentication/result/Authentication.java similarity index 96% rename from lib/src/main/java/com/auth0/authentication/result/Authentication.java rename to auth0/src/main/java/com/auth0/authentication/result/Authentication.java index 58e2575b..ee54a536 100644 --- a/lib/src/main/java/com/auth0/authentication/result/Authentication.java +++ b/auth0/src/main/java/com/auth0/authentication/result/Authentication.java @@ -25,12 +25,14 @@ package com.auth0.authentication.result; +import com.auth0.request.AuthenticationRequest; + import static com.auth0.util.CheckHelper.checkArgument; /** * The result of a successful authentication against Auth0 * Contains the logged in user's {@link Credentials} and {@link UserProfile}. - * @see com.auth0.authentication.AuthenticationAPIClient#getProfileAfter(com.auth0.request.ParameterizableRequest) + * @see com.auth0.authentication.AuthenticationAPIClient#getProfileAfter(AuthenticationRequest) */ public class Authentication { diff --git a/lib/src/main/java/com/auth0/authentication/result/Credentials.java b/auth0/src/main/java/com/auth0/authentication/result/Credentials.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/result/Credentials.java rename to auth0/src/main/java/com/auth0/authentication/result/Credentials.java diff --git a/lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java b/auth0/src/main/java/com/auth0/authentication/result/DatabaseUser.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/result/DatabaseUser.java rename to auth0/src/main/java/com/auth0/authentication/result/DatabaseUser.java diff --git a/lib/src/main/java/com/auth0/authentication/result/Delegation.java b/auth0/src/main/java/com/auth0/authentication/result/Delegation.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/result/Delegation.java rename to auth0/src/main/java/com/auth0/authentication/result/Delegation.java diff --git a/lib/src/main/java/com/auth0/authentication/result/UserIdentity.java b/auth0/src/main/java/com/auth0/authentication/result/UserIdentity.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/result/UserIdentity.java rename to auth0/src/main/java/com/auth0/authentication/result/UserIdentity.java diff --git a/lib/src/main/java/com/auth0/authentication/result/UserProfile.java b/auth0/src/main/java/com/auth0/authentication/result/UserProfile.java similarity index 100% rename from lib/src/main/java/com/auth0/authentication/result/UserProfile.java rename to auth0/src/main/java/com/auth0/authentication/result/UserProfile.java diff --git a/lib/src/main/java/com/auth0/callback/BaseCallback.java b/auth0/src/main/java/com/auth0/callback/BaseCallback.java similarity index 100% rename from lib/src/main/java/com/auth0/callback/BaseCallback.java rename to auth0/src/main/java/com/auth0/callback/BaseCallback.java diff --git a/lib/src/main/java/com/auth0/callback/Callback.java b/auth0/src/main/java/com/auth0/callback/Callback.java similarity index 100% rename from lib/src/main/java/com/auth0/callback/Callback.java rename to auth0/src/main/java/com/auth0/callback/Callback.java diff --git a/lib/src/main/java/com/auth0/request/AuthenticationRequest.java b/auth0/src/main/java/com/auth0/request/AuthenticationRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/AuthenticationRequest.java rename to auth0/src/main/java/com/auth0/request/AuthenticationRequest.java diff --git a/lib/src/main/java/com/auth0/request/AuthorizableRequest.java b/auth0/src/main/java/com/auth0/request/AuthorizableRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/AuthorizableRequest.java rename to auth0/src/main/java/com/auth0/request/AuthorizableRequest.java diff --git a/lib/src/main/java/com/auth0/request/ParameterizableRequest.java b/auth0/src/main/java/com/auth0/request/ParameterizableRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/ParameterizableRequest.java rename to auth0/src/main/java/com/auth0/request/ParameterizableRequest.java diff --git a/lib/src/main/java/com/auth0/request/Request.java b/auth0/src/main/java/com/auth0/request/Request.java similarity index 100% rename from lib/src/main/java/com/auth0/request/Request.java rename to auth0/src/main/java/com/auth0/request/Request.java diff --git a/lib/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java b/auth0/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java rename to auth0/src/main/java/com/auth0/request/internal/BaseAuthenticationRequest.java diff --git a/lib/src/main/java/com/auth0/request/internal/BaseRequest.java b/auth0/src/main/java/com/auth0/request/internal/BaseRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/BaseRequest.java rename to auth0/src/main/java/com/auth0/request/internal/BaseRequest.java diff --git a/lib/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java b/auth0/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java rename to auth0/src/main/java/com/auth0/request/internal/JsonRequestBodyBuilder.java diff --git a/lib/src/main/java/com/auth0/request/internal/RequestFactory.java b/auth0/src/main/java/com/auth0/request/internal/RequestFactory.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/RequestFactory.java rename to auth0/src/main/java/com/auth0/request/internal/RequestFactory.java diff --git a/lib/src/main/java/com/auth0/request/internal/SimpleRequest.java b/auth0/src/main/java/com/auth0/request/internal/SimpleRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/SimpleRequest.java rename to auth0/src/main/java/com/auth0/request/internal/SimpleRequest.java diff --git a/lib/src/main/java/com/auth0/request/internal/VoidRequest.java b/auth0/src/main/java/com/auth0/request/internal/VoidRequest.java similarity index 100% rename from lib/src/main/java/com/auth0/request/internal/VoidRequest.java rename to auth0/src/main/java/com/auth0/request/internal/VoidRequest.java diff --git a/lib/src/main/java/com/auth0/util/Base64.java b/auth0/src/main/java/com/auth0/util/Base64.java similarity index 100% rename from lib/src/main/java/com/auth0/util/Base64.java rename to auth0/src/main/java/com/auth0/util/Base64.java diff --git a/lib/src/main/java/com/auth0/util/BaseTelemetry.java b/auth0/src/main/java/com/auth0/util/BaseTelemetry.java similarity index 100% rename from lib/src/main/java/com/auth0/util/BaseTelemetry.java rename to auth0/src/main/java/com/auth0/util/BaseTelemetry.java diff --git a/lib/src/main/java/com/auth0/util/CheckHelper.java b/auth0/src/main/java/com/auth0/util/CheckHelper.java similarity index 100% rename from lib/src/main/java/com/auth0/util/CheckHelper.java rename to auth0/src/main/java/com/auth0/util/CheckHelper.java diff --git a/lib/src/main/java/com/auth0/util/Telemetry.java b/auth0/src/main/java/com/auth0/util/Telemetry.java similarity index 100% rename from lib/src/main/java/com/auth0/util/Telemetry.java rename to auth0/src/main/java/com/auth0/util/Telemetry.java diff --git a/lib/src/test/java/com/auth0/Auth0Test.java b/auth0/src/test/java/com/auth0/Auth0Test.java similarity index 100% rename from lib/src/test/java/com/auth0/Auth0Test.java rename to auth0/src/test/java/com/auth0/Auth0Test.java diff --git a/lib/src/test/java/com/auth0/UserProfileTest.java b/auth0/src/test/java/com/auth0/UserProfileTest.java similarity index 100% rename from lib/src/test/java/com/auth0/UserProfileTest.java rename to auth0/src/test/java/com/auth0/UserProfileTest.java diff --git a/lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java similarity index 100% rename from lib/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java rename to auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java diff --git a/lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java b/auth0/src/test/java/com/auth0/authentication/ParameterBuilderTest.java similarity index 100% rename from lib/src/test/java/com/auth0/authentication/ParameterBuilderTest.java rename to auth0/src/test/java/com/auth0/authentication/ParameterBuilderTest.java diff --git a/lib/src/test/java/com/auth0/request/internal/BaseRequestTest.java b/auth0/src/test/java/com/auth0/request/internal/BaseRequestTest.java similarity index 100% rename from lib/src/test/java/com/auth0/request/internal/BaseRequestTest.java rename to auth0/src/test/java/com/auth0/request/internal/BaseRequestTest.java diff --git a/lib/src/test/java/com/auth0/util/AuthenticationAPI.java b/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java similarity index 100% rename from lib/src/test/java/com/auth0/util/AuthenticationAPI.java rename to auth0/src/test/java/com/auth0/util/AuthenticationAPI.java diff --git a/lib/src/test/java/com/auth0/util/BaseTelemetryTest.java b/auth0/src/test/java/com/auth0/util/BaseTelemetryTest.java similarity index 100% rename from lib/src/test/java/com/auth0/util/BaseTelemetryTest.java rename to auth0/src/test/java/com/auth0/util/BaseTelemetryTest.java diff --git a/lib/src/test/java/com/auth0/util/CallbackMatcher.java b/auth0/src/test/java/com/auth0/util/CallbackMatcher.java similarity index 100% rename from lib/src/test/java/com/auth0/util/CallbackMatcher.java rename to auth0/src/test/java/com/auth0/util/CallbackMatcher.java diff --git a/lib/src/test/java/com/auth0/util/MockBaseCallback.java b/auth0/src/test/java/com/auth0/util/MockBaseCallback.java similarity index 100% rename from lib/src/test/java/com/auth0/util/MockBaseCallback.java rename to auth0/src/test/java/com/auth0/util/MockBaseCallback.java diff --git a/settings.gradle b/settings.gradle index 0baf2b62..4e5216dd 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,2 @@ rootProject.name = 'auth0-java' -include 'lib' +include 'auth0' From a9dec54b4e2fcb4ee2b5beedbec15a973a241f2f Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 14:24:24 -0300 Subject: [PATCH 69/89] Bintray and Maven plugins --- auth0/build.gradle | 3 +++ bintray.gradle | 33 +++++++++++++++++++++++++++++++++ build.gradle | 11 +++++++++++ maven.gradle | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+) create mode 100644 bintray.gradle create mode 100644 maven.gradle diff --git a/auth0/build.gradle b/auth0/build.gradle index 3b2c19f9..48d1cb29 100644 --- a/auth0/build.gradle +++ b/auth0/build.gradle @@ -36,6 +36,9 @@ artifacts { archives javadocJar } +apply from: '../maven.gradle' +apply from: '../bintray.gradle' + def defineVersion() { def current = describeGit(false) def snapshot = current == null diff --git a/bintray.gradle b/bintray.gradle new file mode 100644 index 00000000..40d05107 --- /dev/null +++ b/bintray.gradle @@ -0,0 +1,33 @@ +def bintrayUser = getProperty('bintray.user') +def bintrayApiKey = getProperty('bintray.key') +def bintrayPassphrase = getProperty('bintray.gpg.password') + +if (bintrayUser != null && bintrayApiKey != null && bintrayPassphrase != null) { + apply plugin: 'com.jfrog.bintray' + bintray { + user = bintrayUser + key = bintrayApiKey + configurations = ['archives'] + dryRun = project.version.endsWith("-SNAPSHOT") + publish = false + pkg { + repo = 'lock-android' + name = project.name + desc = 'Java client library for the Auth0 platform' + websiteUrl = 'https://github.com/auth0/auth0-api-java' + vcsUrl = 'scm:git@github.com:auth0/auth0-api-java.git' + licenses = ["MIT"] + userOrg = 'auth0' + publish = false + version { + gpg { + sign = true + passphrase = bintrayPassphrase + } + vcsTag = project.version + name = project.version + released = new Date() + } + } + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 27685e36..763870fb 100644 --- a/build.gradle +++ b/build.gradle @@ -6,3 +6,14 @@ allprojects { } } +buildscript { + repositories { + jcenter() + } + + dependencies { + classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.6' + } +} + + diff --git a/maven.gradle b/maven.gradle new file mode 100644 index 00000000..2cd60b22 --- /dev/null +++ b/maven.gradle @@ -0,0 +1,37 @@ +apply plugin: 'maven' + +install { + repositories.mavenInstaller { + pom { + project { + packaging 'jar' + artifactId 'auth0' + + name 'Auth0' + description 'Java client library for the Auth0 platform' + url 'https://github.com/auth0/auth0-api-java' + + licenses { + license { + name 'The MIT License (MIT)' + url 'https://raw.githubusercontent.com/auth0/auth0-api-java/master/LICENSE' + distribution 'repo' + } + } + developers { + developer { + id 'hzalaz' + name 'Hernan Zalazar' + email 'hernan@auth0.com' + } + } + scm { + connection 'scm:git@github.com:auth0/auth0-api-java.git' + developerConnection 'scm:git@github.com:auth0/auth0-api-java.git' + url 'https://github.com/auth0/auth0-api-java' + + } + } + } + } +} \ No newline at end of file From a56fa2c4e0943d74935bce10a1e925888a1942bb Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 14:27:22 -0300 Subject: [PATCH 70/89] Release 0.1.0 --- auth0/src/main/java/com/auth0/BuildConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index 50e6ad77..f86854d1 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -2,12 +2,12 @@ abstract class BuildConfig { - private BuildConfig() {}; + private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "1.0.0"; + public static final String VERSION = "0.1.0"; /** * Name of the library auth0-java */ From 93a08b0551d71bd49050dff82323114327690f41 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 14:29:24 -0300 Subject: [PATCH 71/89] Next development iteration --- CHANGELOG.md | 17 +++++++++++++++++ auth0/src/main/java/com/auth0/BuildConfig.java | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..00acc235 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Change Log + +## [0.1.0](https://github.com/auth0/auth0-api-java/tree/0.1.0) (2016-03-18) +**Merged pull requests:** + +- Provide access to the ParameterBuilder inside every request [\#15](https://github.com/auth0/auth0-api-java/pull/15) ([lbalmaceda](https://github.com/lbalmaceda)) +- let UserProfile implement Serializable [\#13](https://github.com/auth0/auth0-api-java/pull/13) ([lbalmaceda](https://github.com/lbalmaceda)) +- Change package structure and introduced new way to include metrics [\#7](https://github.com/auth0/auth0-api-java/pull/7) ([hzalaz](https://github.com/hzalaz)) +- Remove everything related to Application [\#6](https://github.com/auth0/auth0-api-java/pull/6) ([nikolaseu](https://github.com/nikolaseu)) +- Avoid using magic string [\#5](https://github.com/auth0/auth0-api-java/pull/5) ([hzalaz](https://github.com/hzalaz)) +- Travis CI integration [\#4](https://github.com/auth0/auth0-api-java/pull/4) ([lbalmaceda](https://github.com/lbalmaceda)) +- Add sync \(blocking\) mode to all requests [\#3](https://github.com/auth0/auth0-api-java/pull/3) ([nikolaseu](https://github.com/nikolaseu)) +- Authentication api [\#1](https://github.com/auth0/auth0-api-java/pull/1) ([nikolaseu](https://github.com/nikolaseu)) + + + +\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index f86854d1..bebae0b7 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -7,7 +7,7 @@ private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "0.1.0"; + public static final String VERSION = "0.2.0-SNAPSHOT"; /** * Name of the library auth0-java */ From cf1774c1a5c54cc922bc0b7c1d17f685d39b69a7 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 14:36:51 -0300 Subject: [PATCH 72/89] Fix build --- bintray.gradle | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/bintray.gradle b/bintray.gradle index 40d05107..c1519981 100644 --- a/bintray.gradle +++ b/bintray.gradle @@ -1,8 +1,7 @@ -def bintrayUser = getProperty('bintray.user') -def bintrayApiKey = getProperty('bintray.key') -def bintrayPassphrase = getProperty('bintray.gpg.password') - -if (bintrayUser != null && bintrayApiKey != null && bintrayPassphrase != null) { +if (hasProperty('bintray.user') && hasProperty('bintray.key') && hasProperty('bintray.gpg.password')) { + def bintrayUser = getProperty('bintray.user') + def bintrayApiKey = getProperty('bintray.key') + def bintrayPassphrase = getProperty('bintray.gpg.password') apply plugin: 'com.jfrog.bintray' bintray { user = bintrayUser From cae291a953e16151f7f1251a27a774a803178cb5 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 15:43:49 -0300 Subject: [PATCH 73/89] Make SignUpRequest a AuthenticationRequest --- .../auth0/authentication/SignUpRequest.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/auth0/src/main/java/com/auth0/authentication/SignUpRequest.java b/auth0/src/main/java/com/auth0/authentication/SignUpRequest.java index 43ef465e..6ada3864 100644 --- a/auth0/src/main/java/com/auth0/authentication/SignUpRequest.java +++ b/auth0/src/main/java/com/auth0/authentication/SignUpRequest.java @@ -36,7 +36,7 @@ /** * Represent a request that creates a user in a Auth0 Database connection and then logs in. */ -public class SignUpRequest implements Request { +public class SignUpRequest implements Request, AuthenticationRequest { private final DatabaseConnectionRequest signUpRequest; private final AuthenticationRequest authenticationRequest; @@ -77,6 +77,24 @@ public SignUpRequest setScope(String scope) { return this; } + @Override + public AuthenticationRequest setDevice(String device) { + authenticationRequest.setDevice(device); + return this; + } + + @Override + public AuthenticationRequest setAccessToken(String accessToken) { + authenticationRequest.setAccessToken(accessToken); + return this; + } + + @Override + public AuthenticationRequest setGrantType(String grantType) { + authenticationRequest.setGrantType(grantType); + return this; + } + /** * Set the connection used to authenticate * @param connection name From f556e2936c415a6e255311674c061224155904ae Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Fri, 18 Mar 2016 16:02:35 -0300 Subject: [PATCH 74/89] Release 0.1.1 --- README.md | 4 ++-- auth0/src/main/java/com/auth0/BuildConfig.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9cc11b3c..75ece41f 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ Get Auth0 Java via Maven: com.auth0 auth0-java - 0.0.1 + 0.1.1 ``` or Gradle: ```gradle -compile 'com.auth0:auth0-java:0.0.1' +compile 'com.auth0:auth0-java:0.1.1' ``` ## Usage diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index bebae0b7..ed89d663 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -7,7 +7,7 @@ private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "0.2.0-SNAPSHOT"; + public static final String VERSION = "0.1.1"; /** * Name of the library auth0-java */ From 1dc3d72e94ae0c5a317a7494b136e2c9a904e16b Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Mon, 21 Mar 2016 09:58:27 -0300 Subject: [PATCH 75/89] Next development iteration --- CHANGELOG.md | 25 ++++++++++++------- README.md | 15 ++++++++--- .../src/main/java/com/auth0/BuildConfig.java | 2 +- 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00acc235..566d4b23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,23 @@ # Change Log -## [0.1.0](https://github.com/auth0/auth0-api-java/tree/0.1.0) (2016-03-18) +## [0.1.1](https://github.com/auth0/auth0-java/tree/0.1.1) (2016-03-18) +[Full Changelog](https://github.com/auth0/auth0-java/compare/0.1.0...0.1.1) + +**Merged pull requests:** + +- Make SignUpRequest an AuthenticationRequest [\#17](https://github.com/auth0/auth0-java/pull/17) ([hzalaz](https://github.com/hzalaz)) + +## [0.1.0](https://github.com/auth0/auth0-java/tree/0.1.0) (2016-03-18) **Merged pull requests:** -- Provide access to the ParameterBuilder inside every request [\#15](https://github.com/auth0/auth0-api-java/pull/15) ([lbalmaceda](https://github.com/lbalmaceda)) -- let UserProfile implement Serializable [\#13](https://github.com/auth0/auth0-api-java/pull/13) ([lbalmaceda](https://github.com/lbalmaceda)) -- Change package structure and introduced new way to include metrics [\#7](https://github.com/auth0/auth0-api-java/pull/7) ([hzalaz](https://github.com/hzalaz)) -- Remove everything related to Application [\#6](https://github.com/auth0/auth0-api-java/pull/6) ([nikolaseu](https://github.com/nikolaseu)) -- Avoid using magic string [\#5](https://github.com/auth0/auth0-api-java/pull/5) ([hzalaz](https://github.com/hzalaz)) -- Travis CI integration [\#4](https://github.com/auth0/auth0-api-java/pull/4) ([lbalmaceda](https://github.com/lbalmaceda)) -- Add sync \(blocking\) mode to all requests [\#3](https://github.com/auth0/auth0-api-java/pull/3) ([nikolaseu](https://github.com/nikolaseu)) -- Authentication api [\#1](https://github.com/auth0/auth0-api-java/pull/1) ([nikolaseu](https://github.com/nikolaseu)) +- Provide access to the ParameterBuilder inside every request [\#15](https://github.com/auth0/auth0-java/pull/15) ([lbalmaceda](https://github.com/lbalmaceda)) +- let UserProfile implement Serializable [\#13](https://github.com/auth0/auth0-java/pull/13) ([lbalmaceda](https://github.com/lbalmaceda)) +- Change package structure and introduced new way to include metrics [\#7](https://github.com/auth0/auth0-java/pull/7) ([hzalaz](https://github.com/hzalaz)) +- Remove everything related to Application [\#6](https://github.com/auth0/auth0-java/pull/6) ([nikolaseu](https://github.com/nikolaseu)) +- Avoid using magic string [\#5](https://github.com/auth0/auth0-java/pull/5) ([hzalaz](https://github.com/hzalaz)) +- Travis CI integration [\#4](https://github.com/auth0/auth0-java/pull/4) ([lbalmaceda](https://github.com/lbalmaceda)) +- Add sync \(blocking\) mode to all requests [\#3](https://github.com/auth0/auth0-java/pull/3) ([nikolaseu](https://github.com/nikolaseu)) +- Authentication api [\#1](https://github.com/auth0/auth0-java/pull/1) ([nikolaseu](https://github.com/nikolaseu)) diff --git a/README.md b/README.md index 75ece41f..06766f62 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # Auth0 Java -[![Build status][travis-ci-badge]](travis-ci-url) +[![Build][travis-ci-badge]][travis-ci-url] +[![MIT][mit-badge]][mit-url] +[![Maven][maven-badge]][maven-url] +[![JCenter][jcenter-badge]][jcenter-url] Java client library for the [Auth0](https://auth0.com) platform. @@ -121,5 +124,11 @@ This project is licensed under the MIT license. See the [LICENSE](LICENSE) file -[travis-ci-badge]: https://travis-ci.org/auth0/auth0-api-java.svg?branch=master -[tavis-ci-url]: https://travis-ci.org/auth0/auth0-api-java \ No newline at end of file +[travis-ci-badge]: https://travis-ci.org/auth0/auth0-java.svg?branch=master +[travis-ci-url]: https://travis-ci.org/auth0/auth0-java +[mit-badge]: http://img.shields.io/:license-mit-blue.svg?style=flat +[mit-url]: https://raw.githubusercontent.com/auth0/auth0-java/master/LICENSE +[maven-badge]: https://img.shields.io/maven-central/v/com.auth0/auth0.svg +[maven-url]: http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.auth0%22%20AND%20a%3A%22auth0%22 +[jcenter-badge]: https://api.bintray.com/packages/auth0/lock-android/auth0/images/download.svg +[jcenter-url]: https://bintray.com/auth0/lock-android/auth0/_latestVersion diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index ed89d663..bebae0b7 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -7,7 +7,7 @@ private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "0.1.1"; + public static final String VERSION = "0.2.0-SNAPSHOT"; /** * Name of the library auth0-java */ From ecb607356f6654cfad281d0774e92f2b1e420011 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 29 Mar 2016 11:33:35 -0300 Subject: [PATCH 76/89] Update README.md [skip ci] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 06766f62..aeec30a6 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Get Auth0 Java via Maven: ```xml com.auth0 - auth0-java + auth0 0.1.1 ``` @@ -22,7 +22,7 @@ Get Auth0 Java via Maven: or Gradle: ```gradle -compile 'com.auth0:auth0-java:0.1.1' +compile 'com.auth0:auth0:0.1.1' ``` ## Usage From 97c7053437f9bda633331a1cc8e4fe119a6bda64 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 5 Apr 2016 11:36:54 -0300 Subject: [PATCH 77/89] Update telemetry classes --- auth0/build.gradle | 4 ++ auth0/src/main/java/com/auth0/Auth0.java | 4 +- .../java/com/auth0/util/BaseTelemetry.java | 35 ------------ .../main/java/com/auth0/util/Telemetry.java | 53 ++++++++++++++++--- ...eTelemetryTest.java => TelemetryTest.java} | 8 +-- 5 files changed, 56 insertions(+), 48 deletions(-) delete mode 100644 auth0/src/main/java/com/auth0/util/BaseTelemetry.java rename auth0/src/test/java/com/auth0/util/{BaseTelemetryTest.java => TelemetryTest.java} (78%) diff --git a/auth0/build.gradle b/auth0/build.gradle index 48d1cb29..16d43092 100644 --- a/auth0/build.gradle +++ b/auth0/build.gradle @@ -1,5 +1,9 @@ apply plugin: 'java' +compileJava { + sourceCompatibility "1.7" +} + dependencies { compile 'com.squareup.okhttp:okhttp:2.5.0' compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1' diff --git a/auth0/src/main/java/com/auth0/Auth0.java b/auth0/src/main/java/com/auth0/Auth0.java index 29ae2754..0cd33c7b 100644 --- a/auth0/src/main/java/com/auth0/Auth0.java +++ b/auth0/src/main/java/com/auth0/Auth0.java @@ -25,7 +25,6 @@ package com.auth0; import com.auth0.authentication.AuthenticationAPIClient; -import com.auth0.util.BaseTelemetry; import com.auth0.util.Telemetry; import com.squareup.okhttp.HttpUrl; @@ -79,8 +78,7 @@ public Auth0(String clientId, String clientSecret, String domain, String configu this.clientSecret = clientSecret; this.domainUrl = ensureUrlString(domain); this.configurationUrl = resolveConfiguration(configurationDomain, this.domainUrl); - this.telemetry = new BaseTelemetry(); - this.telemetry.usingLibrary(BuildConfig.NAME, BuildConfig.VERSION); + this.telemetry = new Telemetry(BuildConfig.NAME, BuildConfig.VERSION); } /** diff --git a/auth0/src/main/java/com/auth0/util/BaseTelemetry.java b/auth0/src/main/java/com/auth0/util/BaseTelemetry.java deleted file mode 100644 index ae3c7064..00000000 --- a/auth0/src/main/java/com/auth0/util/BaseTelemetry.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.auth0.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.HashMap; -import java.util.Map; - -public class BaseTelemetry implements Telemetry { - - private final Map values; - - public BaseTelemetry() { - this.values = new HashMap<>(); - } - - @Override - public void usingLibrary(String name, String version) { - values.put(NAME_KEY, name); - values.put(VERSION_KEY, version); - } - - @Override - public String getValue() { - if (values.isEmpty()) { - return null; - } - try { - String json = new ObjectMapper().writeValueAsString(values); - return Base64.encodeUrlSafe(json); - } catch (JsonProcessingException e) { - return null; - } - } -} diff --git a/auth0/src/main/java/com/auth0/util/Telemetry.java b/auth0/src/main/java/com/auth0/util/Telemetry.java index c49b1d3d..d4a40847 100644 --- a/auth0/src/main/java/com/auth0/util/Telemetry.java +++ b/auth0/src/main/java/com/auth0/util/Telemetry.java @@ -1,10 +1,51 @@ package com.auth0.util; -public interface Telemetry { - String NAME_KEY = "name"; - String VERSION_KEY = "version"; - String HEADER_NAME = "Auth0-Client"; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; - void usingLibrary(String name, String version); - String getValue(); +import java.util.HashMap; +import java.util.Map; + +public class Telemetry { + public static final String HEADER_NAME = "Auth0-Client"; + + private static final String NAME_KEY = "name"; + private static final String VERSION_KEY = "version"; + private static final String LIB_VERSION_KEY = "lib_version"; + + private final String name; + private final String version; + private final String libraryVersion; + + public Telemetry(String name, String version) { + this(name, version, null); + } + + public Telemetry(String name, String version, String libraryVersion) { + this.name = name; + this.version = version; + this.libraryVersion = libraryVersion; + } + + public String getValue() { + Map values = new HashMap<>(); + if (name != null) { + values.put(NAME_KEY, name); + } + if (version != null) { + values.put(VERSION_KEY, version); + } + if (libraryVersion != null) { + values.put(LIB_VERSION_KEY, libraryVersion); + } + if (values.isEmpty()) { + return null; + } + try { + String json = new ObjectMapper().writeValueAsString(values); + return Base64.encodeUrlSafe(json); + } catch (JsonProcessingException e) { + return null; + } + } } diff --git a/auth0/src/test/java/com/auth0/util/BaseTelemetryTest.java b/auth0/src/test/java/com/auth0/util/TelemetryTest.java similarity index 78% rename from auth0/src/test/java/com/auth0/util/BaseTelemetryTest.java rename to auth0/src/test/java/com/auth0/util/TelemetryTest.java index e84669ac..015c9dbc 100644 --- a/auth0/src/test/java/com/auth0/util/BaseTelemetryTest.java +++ b/auth0/src/test/java/com/auth0/util/TelemetryTest.java @@ -8,23 +8,23 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; -public class BaseTelemetryTest { +public class TelemetryTest { - private BaseTelemetry telemetry; + private Telemetry telemetry; @Before public void setUp() throws Exception { - telemetry = new BaseTelemetry(); + telemetry = new Telemetry("auth0-java", "1.0.0"); } @Test public void shouldReturnBase64() throws Exception { - telemetry.usingLibrary("auth0-java", "1.0.0"); assertThat(telemetry.getValue(), is(notNullValue())); } @Test public void shouldReturnNullWhenNoInfoIsProvided() throws Exception { + telemetry = new Telemetry(null, null); assertThat(telemetry.getValue(), is(nullValue())); } } \ No newline at end of file From 91a8e1177529f2465473963eb0836cb6372bb9cd Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 5 Apr 2016 11:47:09 -0300 Subject: [PATCH 78/89] Release 0.1.2 --- auth0/src/main/java/com/auth0/BuildConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index bebae0b7..2e4f6fdc 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -7,7 +7,7 @@ private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "0.2.0-SNAPSHOT"; + public static final String VERSION = "0.1.2"; /** * Name of the library auth0-java */ From 0e7cd8ef60f6f30f7c208398ab71cac0cf27f377 Mon Sep 17 00:00:00 2001 From: Hernan Zalazar Date: Tue, 5 Apr 2016 11:53:08 -0300 Subject: [PATCH 79/89] Next development iteration --- auth0/src/main/java/com/auth0/BuildConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java index 2e4f6fdc..bebae0b7 100644 --- a/auth0/src/main/java/com/auth0/BuildConfig.java +++ b/auth0/src/main/java/com/auth0/BuildConfig.java @@ -7,7 +7,7 @@ private BuildConfig() {} /** * Version of auth0-java */ - public static final String VERSION = "0.1.2"; + public static final String VERSION = "0.2.0-SNAPSHOT"; /** * Name of the library auth0-java */ From 7a8d2c0b2217425417a34e98cecf91ada1a7b025 Mon Sep 17 00:00:00 2001 From: Luciano Balmaceda Date: Fri, 15 Apr 2016 17:43:18 -0300 Subject: [PATCH 80/89] add oauth token endpoint --- .../AuthenticationAPIClient.java | 41 ++++++++++++++++--- .../authentication/ParameterBuilder.java | 3 +- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java b/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java index a5129de4..00a95e34 100644 --- a/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java +++ b/auth0/src/main/java/com/auth0/authentication/AuthenticationAPIClient.java @@ -29,10 +29,10 @@ import com.auth0.authentication.result.DatabaseUser; import com.auth0.authentication.result.Delegation; import com.auth0.authentication.result.UserProfile; -import com.auth0.request.internal.RequestFactory; import com.auth0.request.AuthenticationRequest; import com.auth0.request.ParameterizableRequest; import com.auth0.request.Request; +import com.auth0.request.internal.RequestFactory; import com.auth0.util.Telemetry; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.HttpUrl; @@ -40,6 +40,7 @@ import java.util.Map; +import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE; import static com.auth0.authentication.ParameterBuilder.GRANT_TYPE_PASSWORD; /** @@ -67,8 +68,12 @@ public class AuthenticationAPIClient { private static final String PASSWORDLESS_PATH = "passwordless"; private static final String START_PATH = "start"; private static final String OAUTH_PATH = "oauth"; + private static final String TOKEN_PATH = "token"; private static final String RESOURCE_OWNER_PATH = "ro"; private static final String TOKEN_INFO_PATH = "tokeninfo"; + private static final String OAUTH_CODE_KEY = "code"; + private static final String OAUTH_CODE_VERIFIER_KEY = "code_verifier"; + private static final String REDIRECT_URI_KEY = "redirect_uri"; private final Auth0 auth0; private final OkHttpClient client; @@ -160,7 +165,7 @@ public AuthenticationRequest login(String usernameOrEmail, String password) { * .start(new BaseCallback() { * {@literal}Override * public void onSuccess(Credentials payload) { } - + * * {@literal}Override * public void onFailure(Auth0Exception error) { } * }); @@ -194,7 +199,7 @@ public AuthenticationRequest loginWithOAuthAccessToken(String token, String conn * .start(new BaseCallback() { * {@literal}Override * public void onSuccess(Credentials payload) { } - + * * {@literal}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -223,7 +228,7 @@ public AuthenticationRequest loginWithPhoneNumber(String phoneNumber, String ver * .start(new BaseCallback() { * {@literal}Override * public void onSuccess(Credentials payload) { } - + * * {@literal}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -252,7 +257,7 @@ public AuthenticationRequest loginWithEmail(String email, String verificationCod * .start(new BaseCallback() { * {@literal}Override * public void onSuccess(UserProfile payload) { } - + * * {@literal}@Override * public void onFailure(Auth0Exception error) { } * }); @@ -677,4 +682,30 @@ private ParameterizableRequest profileRequest() { return factory.POST(url, client, mapper, UserProfile.class); } + + /** + * Fetch the token information from Auth0, using the authorization_code grant type + * + * @param authorizationCode the authorization code received from the /authorize call. + * @param codeVerifier the code verifier used when requesting a code to /authorize. + * @param redirectUri the uri to redirect after a successful request. + * @return a request to configure and start + */ + public AuthenticationRequest token(String authorizationCode, String codeVerifier, String redirectUri) { + Map parameters = ParameterBuilder.newBuilder() + .setClientId(getClientId()) + .setGrantType(GRANT_TYPE_AUTHORIZATION_CODE) + .set(OAUTH_CODE_KEY, authorizationCode) + .set(OAUTH_CODE_VERIFIER_KEY, codeVerifier) + .set(REDIRECT_URI_KEY, redirectUri) + .asDictionary(); + + HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() + .addPathSegment(OAUTH_PATH) + .addPathSegment(TOKEN_PATH) + .build(); + + return factory.authenticationPOST(url, client, mapper) + .addAuthenticationParameters(parameters); + } } diff --git a/auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java b/auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java index 212a2107..8204cb04 100644 --- a/auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java +++ b/auth0/src/main/java/com/auth0/authentication/ParameterBuilder.java @@ -32,7 +32,7 @@ /** * Builder for Auth0 Authentication API parameters - * + *

* You can build your parameters like this *


  *     Map parameters = ParameterBuilder.newBuilder()
@@ -49,6 +49,7 @@ public class ParameterBuilder {
 
     public static final String GRANT_TYPE_PASSWORD = "password";
     public static final String GRANT_TYPE_JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
+    public static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code";
 
     public static final String SCOPE_OPENID = "openid";
     public static final String SCOPE_OFFLINE_ACCESS = "openid offline_access";

From a22b2f9e4a5eb99ed70046d5be416bb08f4a2c08 Mon Sep 17 00:00:00 2001
From: Luciano Balmaceda 
Date: Fri, 15 Apr 2016 17:52:19 -0300
Subject: [PATCH 81/89] add oauth token endpoint test

---
 .../AuthenticationAPIClientTest.java          | 27 ++++++++++++++++---
 .../com/auth0/util/AuthenticationAPI.java     | 14 ++++++++++
 2 files changed, 37 insertions(+), 4 deletions(-)

diff --git a/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
index 3cc630dc..32f0b654 100644
--- a/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
+++ b/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
@@ -26,13 +26,11 @@
 
 
 import com.auth0.Auth0;
-import com.auth0.Auth0Exception;
 import com.auth0.authentication.result.Authentication;
 import com.auth0.authentication.result.Credentials;
 import com.auth0.authentication.result.DatabaseUser;
 import com.auth0.authentication.result.Delegation;
 import com.auth0.authentication.result.UserProfile;
-import com.auth0.request.ParameterizableRequest;
 import com.auth0.util.AuthenticationAPI;
 import com.auth0.util.MockBaseCallback;
 import com.fasterxml.jackson.core.type.TypeReference;
@@ -50,7 +48,6 @@
 import static com.auth0.util.AuthenticationAPI.ID_TOKEN;
 import static com.auth0.util.AuthenticationAPI.REFRESH_TOKEN;
 import static com.auth0.util.CallbackMatcher.hasNoError;
-import static com.auth0.util.CallbackMatcher.hasNoPayloadOfType;
 import static com.auth0.util.CallbackMatcher.hasPayload;
 import static com.auth0.util.CallbackMatcher.hasPayloadOfType;
 import static org.hamcrest.Matchers.equalTo;
@@ -769,7 +766,7 @@ public void shouldGetNewIdTokenWithRefreshTokenSync() throws Exception {
 
         assertThat(delegation, is(notNullValue()));
     }
-    
+
     @Test
     public void shouldUnlinkAccount() throws Exception {
         mockAPI.willReturnSuccessfulUnlinkAccount();
@@ -1173,7 +1170,29 @@ public void shouldFetchProfileAfterLoginRequest() throws Exception {
         assertThat(secondRequest.getPath(), equalTo("/tokeninfo"));
 
         assertThat(callback, hasPayloadOfType(Authentication.class));
+    }
+
+    @Test
+    public void shouldGetOAuthToken() throws Exception {
+        mockAPI
+                .willReturnAuthorizationCodeInfo()
+                .willReturnTokenInfo();
 
+        final MockBaseCallback callback = new MockBaseCallback<>();
+        client.token("code", AuthenticationAPI.CODE_VERIFIER, AuthenticationAPI.REDIRECT_URI)
+                .start(callback);
+
+        final RecordedRequest request = mockAPI.takeRequest();
+        assertThat(request.getPath(), equalTo("/oauth/token"));
+
+        Map body = bodyFromRequest(request);
+        assertThat(body, hasEntry("redirect_uri", AuthenticationAPI.REDIRECT_URI));
+        assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE));
+        assertThat(body, hasEntry("client_id", CLIENT_ID));
+        assertThat(body, hasEntry("code_verifier", AuthenticationAPI.CODE_VERIFIER));
+        assertThat(body, hasEntry("code", "code"));
+
+        assertThat(callback, hasPayloadOfType(Credentials.class));
     }
 
     private Map bodyFromRequest(RecordedRequest request) throws java.io.IOException {
diff --git a/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java b/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
index 437ab1f7..146d3a2d 100644
--- a/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
+++ b/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
@@ -40,6 +40,8 @@ public class AuthenticationAPI  {
     public static final String NEW_ID_TOKEN = "NEW_ID_TOKEN";
     public static final int EXPIRES_IN = 1234567890;
     public static final String TOKEN_TYPE = "TOKEN_TYPE";
+    public static final String CODE_VERIFIER = "CODE_VERIFIER";
+    public static final String REDIRECT_URI = "REDIRECT_URI";
 
     private MockWebServer server;
 
@@ -155,6 +157,18 @@ public AuthenticationAPI willReturnTokenInfo() {
         return this;
     }
 
+    public AuthenticationAPI willReturnAuthorizationCodeInfo() {
+        String json = "{\"" +
+                "redirect_uri\": \"" + REDIRECT_URI + "\"," +
+                "\"code_verifier\": \"" + CODE_VERIFIER + "\"," +
+                "\"client_id\":\"U5MhUrbyQHSVWjlEqZSTCBUFABLbJAS3\"," +
+                "\"code\": \"" + CODE_VERIFIER + "\",\n" +
+                "\"grant_type\":\"authorization_code\"" +
+                "}";
+        server.enqueue(responseWithJSON(json, 200));
+        return this;
+    }
+
     public AuthenticationAPI willReturnApplicationResponseWithBody(String body, int statusCode) {
         MockResponse response =  new MockResponse()
                 .setResponseCode(statusCode)

From 9f1328753863f113145b0a836ea03648f6d36462 Mon Sep 17 00:00:00 2001
From: Luciano Balmaceda 
Date: Mon, 18 Apr 2016 11:34:07 -0300
Subject: [PATCH 82/89] rename and fix oauth/token test.

---
 .../AuthenticationAPIClientTest.java          | 10 +++++-----
 .../com/auth0/util/AuthenticationAPI.java     | 19 ++++++++-----------
 2 files changed, 13 insertions(+), 16 deletions(-)

diff --git a/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java b/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
index 32f0b654..ab94127b 100644
--- a/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
+++ b/auth0/src/test/java/com/auth0/authentication/AuthenticationAPIClientTest.java
@@ -1173,24 +1173,24 @@ public void shouldFetchProfileAfterLoginRequest() throws Exception {
     }
 
     @Test
-    public void shouldGetOAuthToken() throws Exception {
+    public void shouldGetOAuthTokens() throws Exception {
         mockAPI
-                .willReturnAuthorizationCodeInfo()
+                .willReturnTokens()
                 .willReturnTokenInfo();
 
         final MockBaseCallback callback = new MockBaseCallback<>();
-        client.token("code", AuthenticationAPI.CODE_VERIFIER, AuthenticationAPI.REDIRECT_URI)
+        client.token("code", "codeVerifier", "http://redirect.uri")
                 .start(callback);
 
         final RecordedRequest request = mockAPI.takeRequest();
         assertThat(request.getPath(), equalTo("/oauth/token"));
 
         Map body = bodyFromRequest(request);
-        assertThat(body, hasEntry("redirect_uri", AuthenticationAPI.REDIRECT_URI));
         assertThat(body, hasEntry("grant_type", ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE));
         assertThat(body, hasEntry("client_id", CLIENT_ID));
-        assertThat(body, hasEntry("code_verifier", AuthenticationAPI.CODE_VERIFIER));
         assertThat(body, hasEntry("code", "code"));
+        assertThat(body, hasEntry("code_verifier", "codeVerifier"));
+        assertThat(body, hasEntry("redirect_uri", "http://redirect.uri"));
 
         assertThat(callback, hasPayloadOfType(Credentials.class));
     }
diff --git a/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java b/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
index 146d3a2d..429722bb 100644
--- a/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
+++ b/auth0/src/test/java/com/auth0/util/AuthenticationAPI.java
@@ -30,7 +30,7 @@
 
 import java.io.IOException;
 
-public class AuthenticationAPI  {
+public class AuthenticationAPI {
 
     public static final String REFRESH_TOKEN = "REFRESH_TOKEN";
     public static final String ID_TOKEN = "ID_TOKEN";
@@ -38,10 +38,8 @@ public class AuthenticationAPI  {
     public static final String BEARER = "BEARER";
     public static final String GENERIC_TOKEN = "GENERIC_TOKEN";
     public static final String NEW_ID_TOKEN = "NEW_ID_TOKEN";
-    public static final int EXPIRES_IN = 1234567890;
     public static final String TOKEN_TYPE = "TOKEN_TYPE";
-    public static final String CODE_VERIFIER = "CODE_VERIFIER";
-    public static final String REDIRECT_URI = "REDIRECT_URI";
+    public static final int EXPIRES_IN = 1234567890;
 
     private MockWebServer server;
 
@@ -157,20 +155,19 @@ public AuthenticationAPI willReturnTokenInfo() {
         return this;
     }
 
-    public AuthenticationAPI willReturnAuthorizationCodeInfo() {
+    public AuthenticationAPI willReturnTokens() {
         String json = "{\"" +
-                "redirect_uri\": \"" + REDIRECT_URI + "\"," +
-                "\"code_verifier\": \"" + CODE_VERIFIER + "\"," +
-                "\"client_id\":\"U5MhUrbyQHSVWjlEqZSTCBUFABLbJAS3\"," +
-                "\"code\": \"" + CODE_VERIFIER + "\",\n" +
-                "\"grant_type\":\"authorization_code\"" +
+                "access_token\": \"" + ACCESS_TOKEN + "\"," +
+                "\"refresh_token\": \"" + REFRESH_TOKEN + "\"," +
+                "\"id_token\":\"" + ID_TOKEN + "\"," +
+                "\"token_type\":\"Bearer\"" +
                 "}";
         server.enqueue(responseWithJSON(json, 200));
         return this;
     }
 
     public AuthenticationAPI willReturnApplicationResponseWithBody(String body, int statusCode) {
-        MockResponse response =  new MockResponse()
+        MockResponse response = new MockResponse()
                 .setResponseCode(statusCode)
                 .addHeader("Content-Type", "application/x-javascript")
                 .setBody(body);

From eded9fd476d6acf548638efbd8b5e421db04114e Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Mon, 18 Apr 2016 20:40:26 -0300
Subject: [PATCH 83/89] Release 0.2.0

---
 auth0/src/main/java/com/auth0/BuildConfig.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
index bebae0b7..add6e619 100644
--- a/auth0/src/main/java/com/auth0/BuildConfig.java
+++ b/auth0/src/main/java/com/auth0/BuildConfig.java
@@ -7,7 +7,7 @@ private BuildConfig() {}
     /**
      * Version of auth0-java
      */
-    public static final String VERSION = "0.2.0-SNAPSHOT";
+    public static final String VERSION = "0.2.0";
     /**
      * Name of the library auth0-java
      */

From 566022dd95a6f03f4488480b5049414e80e41c25 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Mon, 18 Apr 2016 20:44:14 -0300
Subject: [PATCH 84/89] Next development iteration

---
 CHANGELOG.md                                   | 14 ++++++++++++++
 auth0/src/main/java/com/auth0/BuildConfig.java |  2 +-
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 566d4b23..d0e5ac28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,19 @@
 # Change Log
 
+## [0.2.0](https://github.com/auth0/auth0-java/tree/0.2.0) (2016-04-18)
+[Full Changelog](https://github.com/auth0/auth0-java/compare/0.1.2...0.2.0)
+
+**Merged pull requests:**
+
+- add method to call /oauth/token to the AuthenticationAPIClient [\#20](https://github.com/auth0/auth0-java/pull/20) ([lbalmaceda](https://github.com/lbalmaceda))
+
+## [0.1.2](https://github.com/auth0/auth0-java/tree/0.1.2) (2016-04-05)
+[Full Changelog](https://github.com/auth0/auth0-java/compare/0.1.1...0.1.2)
+
+**Merged pull requests:**
+
+- Update telemetry classes [\#19](https://github.com/auth0/auth0-java/pull/19) ([hzalaz](https://github.com/hzalaz))
+
 ## [0.1.1](https://github.com/auth0/auth0-java/tree/0.1.1) (2016-03-18)
 [Full Changelog](https://github.com/auth0/auth0-java/compare/0.1.0...0.1.1)
 
diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
index add6e619..dfdcbbc0 100644
--- a/auth0/src/main/java/com/auth0/BuildConfig.java
+++ b/auth0/src/main/java/com/auth0/BuildConfig.java
@@ -7,7 +7,7 @@ private BuildConfig() {}
     /**
      * Version of auth0-java
      */
-    public static final String VERSION = "0.2.0";
+    public static final String VERSION = "0.3.0-SNAPSHOT";
     /**
      * Name of the library auth0-java
      */

From 075b028ff779811a0b10fe5412cb9b851042d07f Mon Sep 17 00:00:00 2001
From: Luciano Balmaceda 
Date: Thu, 21 Apr 2016 12:46:16 -0300
Subject: [PATCH 85/89] allow to specify telemetry on constructor or setter

---
 auth0/src/main/java/com/auth0/Auth0.java     | 25 +++++++++++++++-----
 auth0/src/test/java/com/auth0/Auth0Test.java | 13 +++++++++-
 2 files changed, 31 insertions(+), 7 deletions(-)

diff --git a/auth0/src/main/java/com/auth0/Auth0.java b/auth0/src/main/java/com/auth0/Auth0.java
index 0cd33c7b..67d89a5b 100644
--- a/auth0/src/main/java/com/auth0/Auth0.java
+++ b/auth0/src/main/java/com/auth0/Auth0.java
@@ -48,8 +48,9 @@ public class Auth0 {
 
     /**
      * Creates a new object using clientId & domain
+     *
      * @param clientId of your Auth0 application
-     * @param domain of your Auth0 account
+     * @param domain   of your Auth0 account
      */
     public Auth0(String clientId, String domain) {
         this(clientId, null, domain, null);
@@ -57,8 +58,9 @@ public Auth0(String clientId, String domain) {
 
     /**
      * Creates a new object using clientId & domain
+     *
      * @param clientId of your Auth0 application
-     * @param domain of your Auth0 account
+     * @param domain   of your Auth0 account
      */
     public Auth0(String clientId, String clientSecret, String domain) {
         this(clientId, clientSecret, domain, null);
@@ -68,9 +70,10 @@ public Auth0(String clientId, String clientSecret, String domain) {
      * Creates a new object using clientId, domain and configuration domain.
      * Useful when using a on-premise auth0 server that is not in the public cloud,
      * otherwise we recommend using the constructor {@link #Auth0(String, String)}
-     * @param clientId of your Auth0 application
-     * @param clientSecret of your Auth0 application. It can be null, specially if used for an Android application
-     * @param domain of your Auth0 account
+     *
+     * @param clientId            of your Auth0 application
+     * @param clientSecret        of your Auth0 application. It can be null, specially if used for an Android application
+     * @param domain              of your Auth0 account
      * @param configurationDomain where Auth0's configuration will be fetched. By default is Auth0 public cloud
      */
     public Auth0(String clientId, String clientSecret, String domain, String configurationDomain) {
@@ -133,6 +136,16 @@ public Telemetry getTelemetry() {
         return telemetry;
     }
 
+
+    /**
+     * Setter for the Telemetry to send in every request to Auth0.
+     *
+     * @param telemetry to send in every request to Auth0
+     */
+    public void setTelemetry(Telemetry telemetry) {
+        this.telemetry = telemetry;
+    }
+
     /**
      * Avoid sending telemetry in every request to Auth0
      */
@@ -148,7 +161,7 @@ private String resolveConfiguration(String configurationDomain, String domainUrl
             if (host.endsWith(DOT_AUTH0_DOT_COM)) {
                 String[] parts = host.split("\\.");
                 if (parts.length > 3) {
-                    url = "https://cdn." + parts[parts.length-3] + DOT_AUTH0_DOT_COM;
+                    url = "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM;
                 } else {
                     url = AUTH0_US_CDN_URL;
                 }
diff --git a/auth0/src/test/java/com/auth0/Auth0Test.java b/auth0/src/test/java/com/auth0/Auth0Test.java
index ce618d32..9139e9d8 100644
--- a/auth0/src/test/java/com/auth0/Auth0Test.java
+++ b/auth0/src/test/java/com/auth0/Auth0Test.java
@@ -25,6 +25,7 @@
 package com.auth0;
 
 import com.auth0.authentication.AuthenticationAPIClient;
+import com.auth0.util.Telemetry;
 
 import org.junit.Test;
 
@@ -32,11 +33,13 @@
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.notNullValue;
 import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertThat;
 
 public class Auth0Test {
 
     private static final String CLIENT_ID = "CLIENT_ID";
+    private static final String CLIENT_SECRET = "CLIENT_SECRET";
+    private static final String CONFIGURATION_DOMAIN = "CONFIGURATION_DOMAIN";
     private static final String DOMAIN = "samples.auth0.com";
     private static final String CONFIG_DOMAIN_CUSTOM = "config.mydomain.com";
     private static final String EU_DOMAIN = "samples.eu.auth0.com";
@@ -112,4 +115,12 @@ public void shouldNotReturnTelemetryWhenExplicitlyDisabledThem() throws Exceptio
         auth0.doNotSendTelemetry();
         assertThat(auth0.getTelemetry(), is(nullValue()));
     }
+
+    @Test
+    public void shouldSetCustomTelemetry() throws Exception {
+        Telemetry customTelemetry = new Telemetry("custom", "9.9.9", "1.1.1");
+        Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN);
+        auth0.setTelemetry(customTelemetry);
+        assertThat(auth0.getTelemetry(), is(equalTo(customTelemetry)));
+    }
 }
\ No newline at end of file

From 39367f4288fe2cd14548e0ef85060de4c87521ab Mon Sep 17 00:00:00 2001
From: Luciano Balmaceda 
Date: Thu, 21 Apr 2016 13:28:44 -0300
Subject: [PATCH 86/89] make public the BuildConfig class

---
 auth0/src/main/java/com/auth0/BuildConfig.java | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
index dfdcbbc0..96b72ed2 100644
--- a/auth0/src/main/java/com/auth0/BuildConfig.java
+++ b/auth0/src/main/java/com/auth0/BuildConfig.java
@@ -1,8 +1,6 @@
 package com.auth0;
 
-abstract class BuildConfig {
-
-    private BuildConfig() {}
+public abstract class BuildConfig {
 
     /**
      * Version of auth0-java

From fd8870c74bcf7bab1ae35bbc3acd4c7e9c377f29 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Mon, 25 Apr 2016 16:22:51 -0300
Subject: [PATCH 87/89] Release 0.2.1

---
 auth0/src/main/java/com/auth0/BuildConfig.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
index 96b72ed2..e7856492 100644
--- a/auth0/src/main/java/com/auth0/BuildConfig.java
+++ b/auth0/src/main/java/com/auth0/BuildConfig.java
@@ -5,7 +5,7 @@ public abstract class BuildConfig {
     /**
      * Version of auth0-java
      */
-    public static final String VERSION = "0.3.0-SNAPSHOT";
+    public static final String VERSION = "0.2.1";
     /**
      * Name of the library auth0-java
      */

From 7b6471c3db303a686ef4c83a7f482256e4a2a0e4 Mon Sep 17 00:00:00 2001
From: Hernan Zalazar 
Date: Mon, 25 Apr 2016 16:24:29 -0300
Subject: [PATCH 88/89] Next development iteration

---
 CHANGELOG.md                                   | 7 +++++++
 auth0/src/main/java/com/auth0/BuildConfig.java | 2 +-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0e5ac28..aff62106 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
 # Change Log
 
+## [0.2.1](https://github.com/auth0/auth0-java/tree/0.2.1) (2016-04-25)
+[Full Changelog](https://github.com/auth0/auth0-java/compare/0.2.0...0.2.1)
+
+**Merged pull requests:**
+
+- Customise Telemetry info [\#21](https://github.com/auth0/auth0-java/pull/21) ([lbalmaceda](https://github.com/lbalmaceda))
+
 ## [0.2.0](https://github.com/auth0/auth0-java/tree/0.2.0) (2016-04-18)
 [Full Changelog](https://github.com/auth0/auth0-java/compare/0.1.2...0.2.0)
 
diff --git a/auth0/src/main/java/com/auth0/BuildConfig.java b/auth0/src/main/java/com/auth0/BuildConfig.java
index e7856492..96b72ed2 100644
--- a/auth0/src/main/java/com/auth0/BuildConfig.java
+++ b/auth0/src/main/java/com/auth0/BuildConfig.java
@@ -5,7 +5,7 @@ public abstract class BuildConfig {
     /**
      * Version of auth0-java
      */
-    public static final String VERSION = "0.2.1";
+    public static final String VERSION = "0.3.0-SNAPSHOT";
     /**
      * Name of the library auth0-java
      */

From 45e2adefe508f28437ae07b5635a911c5262e1e9 Mon Sep 17 00:00:00 2001
From: "tingold@boundlessgeo.com" 
Date: Fri, 17 Jun 2016 09:15:17 -0400
Subject: [PATCH 89/89] changed to java 8 and removed doc build

---
 .gitignore         |  3 ++-
 auth0/build.gradle | 18 +++++++++---------
 2 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/.gitignore b/.gitignore
index ab746e30..a8a3133c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,4 +29,5 @@ gen/
 *.log
 
 # MacOS
-.DS_Store
\ No newline at end of file
+.DS_Store
+/.nb-gradle/
\ No newline at end of file
diff --git a/auth0/build.gradle b/auth0/build.gradle
index 16d43092..343b7081 100644
--- a/auth0/build.gradle
+++ b/auth0/build.gradle
@@ -1,14 +1,14 @@
 apply plugin: 'java'
 
 compileJava {
-    sourceCompatibility "1.7"
+    sourceCompatibility "1.8"
 }
 
 dependencies {
     compile 'com.squareup.okhttp:okhttp:2.5.0'
-    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1'
-    compile 'com.fasterxml.jackson.core:jackson-core:2.4.1'
-    compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.1'
+    compile 'com.fasterxml.jackson.core:jackson-databind:2.6.3'
+    compile 'com.fasterxml.jackson.core:jackson-core:2.6.3'
+    compile 'com.fasterxml.jackson.core:jackson-annotations:2.6.3'
 
     testCompile 'junit:junit:4.12'
     testCompile 'org.hamcrest:hamcrest-integration:1.3'
@@ -30,14 +30,14 @@ task sourcesJar(type: Jar, dependsOn: classes) {
     from sourceSets.main.allSource
 }
 
-task javadocJar(type: Jar, dependsOn: javadoc) {
-    classifier = 'javadoc'
-    from javadoc.destinationDir
-}
+//task javadocJar(type: Jar, dependsOn: javadoc) {
+//    classifier = 'javadoc'
+//    from javadoc.destinationDir
+//}
 
 artifacts {
     archives sourcesJar
-    archives javadocJar
+    //archives javadocJar
 }
 
 apply from: '../maven.gradle'